whitefox 發表於 2023-6-2 17:50:40

[C#] 獲取視窗資訊

public static WindowInfo GetWindowDetail(IntPtr hWnd)
{
    // 視窗類別名
    var lpString = new StringBuilder(512);
    User32.GetClassName(hWnd, lpString, lpString.Capacity);
    var className = lpString.ToString();

    // 視窗標題
    var lptrString = new StringBuilder(512);
    User32.GetWindowText(hWnd, lptrString, lptrString.Capacity);
    var title = lptrString.ToString().Trim();

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

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

    // 視窗所在進程資訊
    var processInfo = ProcessInfosByHwnd.GetInfo(hWnd);
    return new WindowInfo(hWnd, className, title, isVisible, bounds, processInfo);
}User32函數public static class User32
{
   
    public static extern IntPtr GetWindow(IntPtr hwnd, uint windowType);

    public delegate bool WndEnumProc(IntPtr hWnd, int lParam);
   
    public static extern bool EnumWindows(WndEnumProc lpEnumFunc, int lParam);

   
    public static extern IntPtr GetParent(IntPtr hWnd);

   
    public static extern bool IsWindowVisible(IntPtr hWnd);

   
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lptrString, int nMaxCount);

   
    public static extern int GetClassName(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

   
    public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

   
    public static extern bool GetWindowRect(IntPtr hWnd, ref LPRECT rect);


   
    public readonly struct LPRECT
    {
        public readonly int Left;
        public readonly int Top;
        public readonly int Right;
        public readonly int Bottom;
    }
}
頁: [1]
查看完整版本: [C#] 獲取視窗資訊