2010-10-25 180 views
3

是否有可能检测到应用程序是否有控制台窗口?要么使用AllocConsole,要么使用常规控制台应用程序。检测控制台窗口?

编辑:

解决方案(感谢HO1的答案):

public static class ConsoleDetector 
{ 
    private const uint ATTACH_PARENT_PROCESS = 0x0ffffffff; 
    private const int ERROR_ACCESS_DENIED = 5; 
    [DllImport("kernel32.dll", SetLastError = true)] 
    private static extern bool AttachConsole(uint dwProcessId); 
    [DllImport("kernel32", SetLastError = true)] 
    private static extern bool FreeConsole(); 


    /// <summary> 
    /// Gets if the current process has a console window. 
    /// </summary> 
    public static bool HasOne 
    { 
     get 
     { 
      if (AttachConsole(ATTACH_PARENT_PROCESS)) 
      { 
       FreeConsole(); 
       return false; 
      } 

      //If the calling process is already attached to a console, 
      // the error code returned is ERROR_ACCESS_DENIED 
      return Marshal.GetLastWin32Error() == ERROR_ACCESS_DENIED; 
     } 
    } 
} 
+0

当你说控制台窗口是指控制台应用程序还是简单的窗口? – 2010-10-25 13:29:02

+0

难道不明显吗?首先我提到了AllocConsole方法,然后在我的问题中编写了“控制台应用程序”。最后ho1给出了一个提及AttachConsole的答案:) – jgauffin 2010-10-25 13:46:48

回答

3

可能这样做,但一些更合适的方法,我想你可以打电话给AttachConsole并检查它是否失败,ERROR_INVALID_HANDLE(其如果该过程没有控制台,则会发生)。