开发者

Detect console window?

Is it possible to detect if an application has an console window? Either by have used AllocConsole or if it's a regular console application.

Edit:

Solution (thanks to ho1's answer):

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>
    /// G开发者_如何学Cets 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;
        }
    }
}


Probably some neater way of doing it but I suppose you could call AttachConsole and check if it fails with ERROR_INVALID_HANDLE (which it will if the process has no console) or not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜