C#用API如何遍历所有窗口句柄

来源:互联网 发布:阿拉斯加大学 知乎 编辑:程序博客网 时间:2024/05/16 03:15

1.首先需要声明一个委托函数用于 Win32 API - EnumWindows 的回调函数:

private delegatebool WNDENUMPROC(IntPtr hWnd, int lParam); //IntPtr hWnd用int也可以

2.然后利用 C# 中的平台调用声明从 USER32.DLL 库中调用 API - EnumWindows,具体参数请参考 MSDN - Win32 API。

[DllImport("user32.dll")]

private staticextern bool EnumWindows(WNDENUMPROC lpEnumFunc,int lParam);

3.最后实例化委托,调用 EnumWindows。

EnumWindows(delegate(IntPtr hWnd, int lParam) {……},0);

private delegate bool WNDENUMPROC(IntPtr hWnd, int lParam);//用来遍历所有窗口        [DllImport("user32.dll")]         private static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);//获取窗口Text         [DllImport("user32.dll")]         private static extern int GetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);//获取窗口类名         [DllImport("user32.dll")]         private static extern int GetClassNameW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount); //自定义一个类,用来保存句柄信息,在遍历的时候,随便也用空上句柄来获取些信息,呵呵         public struct WindowInfo         
        {             public IntPtr hWnd;             public string szWindowName;             public string szClassName;         }        public WindowInfo[] GetAllDesktopWindows()         { 
//用来保存窗口对象 列表            List<WindowInfo> wndList = new List<WindowInfo>();            //enum all desktop windows             EnumWindows(delegate(IntPtr hWnd, int lParam)             {                 WindowInfo wnd = new WindowInfo();                 StringBuilder sb = new StringBuilder(256);                //get hwnd                 wnd.hWnd = hWnd;                //get window name                  GetWindowTextW(hWnd, sb, sb.Capacity);                 wnd.szWindowName = sb.ToString();                //get window class                 GetClassNameW(hWnd, sb, sb.Capacity);                 wnd.szClassName = sb.ToString();                //add it into list                 wndList.Add(wnd);                 return true;             }, 0);            return wndList.ToArray();         }