Mike
Mike

Reputation: 171

Determine if a window is visible or not using C#

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)

Upvotes: 17

Views: 15973

Answers (4)

Nben
Nben

Reputation: 332

I didn't have success with IsWindowVisible.

turns out I needed IsIconic which means "if window minimized"

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

public static bool GetIsWindowMinimized(IntPtr hWnd)
{
    return IsIconic(hWnd);
}

Upvotes: 0

Paul
Paul

Reputation: 3954

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.

Upvotes: 0

dtb
dtb

Reputation: 217293

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);

Upvotes: 22

Karsten
Karsten

Reputation: 31

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

Upvotes: 1

Related Questions