📜  c# getforegroundwindow - C# 代码示例

📅  最后修改于: 2022-03-11 14:49:10.400000             🧑  作者: Mango

代码示例2
#region Retrieve list of windows

    [DllImport("user32")]
    private static extern int GetWindowLongA(IntPtr hWnd, int index);

    [DllImport("USER32.DLL")]
    private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

    [DllImport("USER32.DLL")]
    private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    private const int GWL_STYLE = -16;

    private const ulong WS_VISIBLE = 0x10000000L;
    private const ulong WS_BORDER = 0x00800000L;
    private const ulong TARGETWINDOW = WS_BORDER | WS_VISIBLE;

    internal class Window
    {
        public string Title;
        public IntPtr Handle;

        public override string ToString()
        {
            return Title;
        }
    }

    private List windows;

    private void GetWindows()
    {
        windows = new List();
        EnumWindows(Callback, 0);
    }

    private bool Callback(IntPtr hwnd, int lParam)
    {
        if (this.Handle != hwnd && (GetWindowLongA(hwnd, GWL_STYLE) & TARGETWINDOW) == TARGETWINDOW)
        {
            StringBuilder sb = new StringBuilder(100);
            GetWindowText(hwnd, sb, sb.Capacity);

            Window t = new Window();
            t.Handle = hwnd;
            t.Title = sb.ToString();
            windows.Add(t);
        }

        return true; //continue enumeration
    }

    #endregion