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数据显示:
作者:唐宋元明清2188
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。