检查窗口是否聚焦

时间:2019-04-15 05:09:11

标签: c# windows winforms

我正在为游戏制作C#叠加层。 它出现在游戏中,但是如果将游戏最小化,它不会隐藏,所以我想知道是否有任何方法可以检查窗口是否最小化/焦点不清晰。我在Google上进行了搜索,但找不到有用的东西。

1 个答案:

答案 0 :(得分:1)

要在具有窗口标题名称或窗口句柄时检查窗口的状态(正常,最大化或最小化),可以使用以下代码:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

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

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

enum WinState
{
    None,
    Maximized,
    Minimized,
    Normal,
}

private static WinState GetWindowState(IntPtr hWnd)
{
    WinState winState = WinState.None;
    if (hWnd != IntPtr.Zero)
    {
        if (IsIconic(hWnd))
        {
            winState = WinState.Minimized;
        }
        else if (IsZoomed(hWnd))
        {
            winState = WinState.Maximized;
        }
        else
        {
            winState = WinState.Normal;
        }
    }

    return winState;
}

private static WinState GetWindowState(string windowCaption)
{
    return GetWindowState((IntPtr)FindWindow(null, windowCaption));
}

用法:

string windowCaption = "New Tab - Google Chrome";
WinState winState = GetWindowState(windowCaption);