15
votes

I have a Console / Form hybrid application in C#, and at the moment, i have to rely on user32.dll to show/hide the console window. But I can't seem to find a way in which i can determine if the console window is hidden or visible (without storing the value myself)

3

3 Answers

19
votes

IsWindowVisible Function:

The IsWindowVisible function retrieves the visibility state of the specified window.

C# Signature from pinvoke.net:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWindowVisible(IntPtr hWnd);
0
votes

Had the same issue now, solved it this way:

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr WindowFromPoint(Point lpPoint);

var mainForm = this; // or any other form you like to check
bool windowIsInvisible =  
    WindowFromPoint(new Point(mainForm.Left, mainForm.Top)) != mainForm.Handle || // topleft invisible
    WindowFromPoint(new Point(mainForm.Left + mainForm.Width - 1, mainForm.Top)) != mainForm.Handle || // topright invisible
    WindowFromPoint(new Point(mainForm.Left, mainForm.Top + mainForm.Height - 1)) != mainForm.Handle || // downleft invisible
    WindowFromPoint(new Point(mainForm.Left + mainForm.Width -1, mainForm.Top + mainForm.Height -1)) != mainForm.Handle; // downright invisible
0
votes

I use this function in a C# console application to determine if the program was launched with or without a console window visible (e.g. via System.Diagnostics.Process.Start() with CreateNoWindow = true).

public static bool IsConsoleVisible()
{
    try
    {
        return Console.WindowHeight > 0;
    }
    catch (System.IO.IOException ex)
    {
        if (ex.Message.Contains("The handle is invalid."))
        {
            return false;
        }
        else
        {
            throw ex;
        }
    }
}

Perhaps this will apply.