如何检查程序是否是从控制台运行? [英] How to check if the program is run from a console?

查看:147
本文介绍了如何检查程序是否是从控制台运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一些转储诊断标准输出的应用程序。

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 )或已标准输出重定向/管道到一个文件中,退出的尽快完成它,

  • 否则(如果它是从一个窗口中运行和控制台窗口是自动生成),然后
    另外等待一个关键preSS退出(让用户读取诊断)窗口消失
  • 前前
  • 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的,因此这个问题。

How do I make that distinction? I suspect that examining the parent process could be a way but I'm not really into WinAPI, hence the question.

我在MinGW的海湾合作​​委员会。

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;
}

这篇关于如何检查程序是否是从控制台运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆