冰楓論壇

標題: [C#] 獲取視窗資訊 [打印本頁]

作者: whitefox    時間: 2023-6-2 17:50
標題: [C#] 獲取視窗資訊
  1. public 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.     var lptrString = new StringBuilder(512);
  9.     User32.GetWindowText(hWnd, lptrString, lptrString.Capacity);
  10.     var title = lptrString.ToString().Trim();

  11.     // 視窗可視性
  12.     var isVisible = User32.IsWindowVisible(hWnd);

  13.     // 視窗位置與大小
  14.     User32.LPRECT rect = default;
  15.     User32.GetWindowRect(hWnd, ref rect);
  16.     var bounds = new Rect(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);

  17.     // 視窗所在進程資訊
  18.     var processInfo = ProcessInfosByHwnd.GetInfo(hWnd);
  19.     return new WindowInfo(hWnd, className, title, isVisible, bounds, processInfo);
  20. }
複製代碼
User32函數
  1. public static class User32
  2. {
  3.     [DllImport("user32.dll", SetLastError = true)]
  4.     public static extern IntPtr GetWindow(IntPtr hwnd, uint windowType);

  5.     public delegate bool WndEnumProc(IntPtr hWnd, int lParam);
  6.     [DllImport("user32")]
  7.     public static extern bool EnumWindows(WndEnumProc lpEnumFunc, int lParam);

  8.     [DllImport("user32")]
  9.     public static extern IntPtr GetParent(IntPtr hWnd);

  10.     [DllImport("user32")]
  11.     public static extern bool IsWindowVisible(IntPtr hWnd);

  12.     [DllImport("user32")]
  13.     public static extern int GetWindowText(IntPtr hWnd, StringBuilder lptrString, int nMaxCount);

  14.     [DllImport("user32")]
  15.     public static extern int GetClassName(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

  16.     [DllImport("user32")]
  17.     public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

  18.     [DllImport("user32")]
  19.     public static extern bool GetWindowRect(IntPtr hWnd, ref LPRECT rect);


  20.     [StructLayout(LayoutKind.Sequential)]
  21.     public readonly struct LPRECT
  22.     {
  23.         public readonly int Left;
  24.         public readonly int Top;
  25.         public readonly int Right;
  26.         public readonly int Bottom;
  27.     }
  28. }
複製代碼





歡迎光臨 冰楓論壇 (https://bingfong.com/) Powered by 冰楓