Console window detection?

Is it possible to determine if the application has a console window? Either use AllocConsole, or use this regular console application.

Edit:

Solution (thanks to the ho1 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>
    /// 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;
        }
    }
}
+3
source share
1 answer

This may be an easier way to do this, but I suppose you could call AttachConsole and see if it works with ERROR_INVALID_HANDLE(what would happen if the process doesn't have a console) or not.

+3
source

Source: https://habr.com/ru/post/1771275/


All Articles