代码之家  ›  专栏  ›  技术社区  ›  jgauffin

检测控制台窗口?

  •  3
  • jgauffin  · 技术社区  · 15 年前

    是否可以检测应用程序是否有控制台窗口?或者是使用了alloconsole,或者是常规的控制台应用程序。

    编辑:

    解决方案(感谢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;
            }
        }
    }
    
    1 回复  |  直到 15 年前
        1
  •  3
  •   Hans Olsson    15 年前

    也许是更整洁的方法,但我想你可以打电话给 AttachConsole 检查是否失败 ERROR_INVALID_HANDLE (如果进程没有控制台,它将执行此操作)或不执行此操作。

    推荐文章