How to check if the program is run from a console?(如何检查程序是否从控制台运行?)
问题描述
我正在编写一个应用程序,它将一些诊断信息转储到标准输出.
I'm writing an application which dumps some diagnostics to the standard output.
我想让应用程序以这种方式工作:
I'd like to have the application work this way:
- 如果它是从独立命令提示符(通过
cmd.exe)运行或将标准输出重定向/管道到文件,则在完成后立即退出, - 否则(如果它是从一个窗口运行并且控制台窗口是自动生成的),那么另外在窗口消失之前等待按键退出(让用户阅读诊断)
- If it is run from a standalone command prompt (via
cmd.exe) or has standard output redirected/piped to a file, exit cleanly as soon as it finished, - Otherwise (if it is run from a window and the console window is spawned automagically), then additionally wait for a keypress before exiting (to let the user read the diagnostics) before the window disappears
我该如何区分?我怀疑检查父进程可能是一种方法,但我并不是真的很喜欢 WinAPI,因此这个问题.
我在 MinGW GCC 上.
I'm on MinGW GCC.
推荐答案
您可以使用 GetConsoleWindow,GetWindowThreadProcessId 和 GetCurrentProcessId 方法.
You can use GetConsoleWindow, GetWindowThreadProcessId and GetCurrentProcessId methods.
1) 首先,您必须使用 GetConsoleWindow 函数检索控制台窗口的当前句柄.
1) First you must retrieve the current handle of the console window using the GetConsoleWindow function.
2) 然后你会得到控制台窗口句柄的进程所有者.
2) Then you get the process owner of the handle of the console window.
3) 最后,将返回的 PID 与应用程序的 PID 进行比较.
3) Finally you compare the returned PID against the PID of your application.
检查此示例(VS C++)
Check this sample (VS C++)
#include "stdafx.h"
#include <iostream>
using namespace std;
#if _WIN32_WINNT < 0x0500
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
#include <windows.h>
#include "Wincon.h"
int _tmain(int argc, _TCHAR* argv[])
{
HWND consoleWnd = GetConsoleWindow();
DWORD dwProcessId;
GetWindowThreadProcessId(consoleWnd, &dwProcessId);
if (GetCurrentProcessId()==dwProcessId)
{
cout << "I have my own console, press enter to exit" << endl;
cin.get();
}
else
{
cout << "This Console is not mine, good bye" << endl;
}
return 0;
}
这篇关于如何检查程序是否从控制台运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查程序是否从控制台运行?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
