C# 獲取所有桌面窗口信息

窗口標題、窗口類名、是否可見、是否最小化、窗口位置和大小、窗口所在進程信息

 1     private static WindowInfo GetWindowDetail(IntPtr hWnd)
 2     {
 3         // 獲取窗口類名。
 4         var lpString = new StringBuilder(512);
 5         User32.GetClassName(hWnd, lpString, lpString.Capacity);
 6         var className = lpString.ToString();
 7 
 8         // 獲取窗口標題。
 9         var lptrString = new StringBuilder(512);
10         User32.GetWindowText(hWnd, lptrString, lptrString.Capacity);
11         var title = lptrString.ToString().Trim();
12 
13         // 獲取窗口可見性。
14         var isVisible = User32.IsWindowVisible(hWnd);
15 
16         // 獲取窗口位置和尺寸。
17         User32.LPRECT rect = default;
18         User32.GetWindowRect(hWnd, ref rect);
19         var bounds = new Rect(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
20 
21         // 獲取窗口所在進程信息
22         var processInfo = ProcessInfosByHwnd.GetInfo(hWnd);
23         return new WindowInfo(hWnd, className, title, isVisible, bounds, processInfo);
24     }

User32函數:

 1     public static class User32
 2     {
 3         [DllImport("user32.dll", SetLastError = true)]
 4         public static extern IntPtr GetWindow(IntPtr hwnd, uint windowType);
 5 
 6         public delegate bool WndEnumProc(IntPtr hWnd, int lParam);
 7         [DllImport("user32")]
 8         public static extern bool EnumWindows(WndEnumProc lpEnumFunc, int lParam);
 9 
10         [DllImport("user32")]
11         public static extern IntPtr GetParent(IntPtr hWnd);
12 
13         [DllImport("user32")]
14         public static extern bool IsWindowVisible(IntPtr hWnd);
15 
16         [DllImport("user32")]
17         public static extern int GetWindowText(IntPtr hWnd, StringBuilder lptrString, int nMaxCount);
18 
19         [DllImport("user32")]
20         public static extern int GetClassName(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
21 
22         [DllImport("user32")]
23         public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
24 
25         [DllImport("user32")]
26         public static extern bool GetWindowRect(IntPtr hWnd, ref LPRECT rect);
27 
28 
29         [StructLayout(LayoutKind.Sequential)]
30         public readonly struct LPRECT
31         {
32             public readonly int Left;
33             public readonly int Top;
34             public readonly int Right;
35             public readonly int Bottom;
36         }
37     }

Demo數據顯示:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章