如何使用 EnumWindows 只获取实际的应用程序窗口?

Bru*_*oLM 1 c# pinvoke

我想要获取所有可以截图的窗口,应用程序窗口。我正在尝试使用EnumWindows.

public delegate bool CallBackPtr(IntPtr hwnd, int lParam);

[DllImport("user32.dll")]
private static extern int EnumWindows(CallBackPtr callPtr, int lPar);

public static List<IntPtr> EnumWindows()
{
    var result = new List<IntPtr>();

    EnumWindows(new User32.CallBackPtr((hwnd, lParam) =>
    {
        result.Add(hwnd);
        return true;
    }), 0);

    return result;
}
Run Code Online (Sandbox Code Playgroud)

然而,这返回的 Windows 数量超出了我的预期,例如:

工具提示

工具提示

黑东西

我只想获取 Windows,例如 Visual Studio、Skype、Explorer、Chrome...

我应该使用其他方法吗?或者我如何检查它是否是我想要抓取的窗口?

Cor*_*son 5

也许检查标题栏的窗口样式可以满足您的要求:

[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

static bool IsAppWindow(IntPtr hWnd)
{
    int style = GetWindowLong(hWnd, -16); // GWL_STYLE

    // check for WS_VISIBLE and WS_CAPTION flags
    // (that the window is visible and has a title bar)
    return (style & 0x10C00000) == 0x10C00000;
}
Run Code Online (Sandbox Code Playgroud)

但这对于一些完全自定义绘制的更高级的应用程序不起作用。