问题描述
我正在编写一个应用程序,它将一些诊断信息转储到标准输出.
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;
}
这篇关于如何检查程序是否从控制台运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)