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;
}
这篇关于如何检查程序是否从控制台运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查程序是否从控制台运行?


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01