首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

C# GetWindowRect API 詳解:獲取窗口屏幕坐標矩形完整指南

     編輯:ASP.NET 基礎

API 簽名與功能

[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

功能: 獲取指定窗口邊框矩形的屏幕坐標(相對於屏幕左上角)。

參數:

  • hWnd:目標窗口句柄
  • lpRect:輸出參數,接收 RECT 結構(Left、Top、Right、Bottom)

返回值: 非零表示成功,零表示失敗(調用 GetLastError 獲取錯誤碼)。

RECT 結構定義

[StructLayout(LayoutKind.Sequential)]
public struct RECT {
    public int Left;   // 左上角 X
    public int Top;    // 左上角 Y
    public int Right;  // 右下角 X
    public int Bottom; // 右下角 Y
}

注意: 必須加 [StructLayout(LayoutKind.Sequential)] 確保記憶體佈局與 Win32 API 一致。

完整調用示例

using System;
using System.Runtime.InteropServices;

public class WindowHelper {
    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
    
    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    
    [StructLayout(LayoutKind.Sequential)]
    public struct RECT {
        public int Left, Top, Right, Bottom;
    }
    
    public static RECT GetWindowRect(string windowTitle) {
        IntPtr hWnd = FindWindow(null, windowTitle);
        if (hWnd == IntPtr.Zero) throw new Exception("窗口未找到");
        
        RECT rect;
        if (!GetWindowRect(hWnd, out rect)) {
            int error = Marshal.GetLastWin32Error();
            throw new System.ComponentModel.Win32Exception(error);
        }
        return rect;
    }
}

// 使用
var rect = WindowHelper.GetWindowRect("計算器");
Console.WriteLine($"Left:{rect.Left}, Top:{rect.Top}, Right:{rect.Right}, Bottom:{rect.Bottom}");
Console.WriteLine($"寬度:{rect.Right - rect.Left}, 高度:{rect.Bottom - rect.Top}");

常見應用場景

  • 窗口位置/大小監控與記錄
  • 自動化測試:驗證窗口狀態
  • 螢幕截圖:確定截取區域
  • 窗口對齊/吸附邊緣邏輯
  • 多顯示器環境下的座標轉換

避坑指南

問題原因解決
返回全零矩形窗口最小化或隱藏調用前確保窗口可見(IsWindowVisible)
座標異常(負值/超大)多顯示器、DPI 縮放使用 GetDpiForWindow 校正,或 SetProcessDpiAwareness
AccessViolationExceptionRECT 結構佈局錯誤加 [StructLayout(LayoutKind.Sequential)],字段順序勿變
FindWindow 返回零標題不完全匹配、類名錯誤用 Spy++ 確認類名/標題,或 EnumWindows 遍歷查找

相關 API 延伸

  • GetClientRect:獲取客戶區域座標(不含邊框/標題欄),相對窗口左上角
  • ScreenToClient / ClientToScreen:屏幕/客戶區座標轉換
  • SetWindowPos:設置窗口位置大小(見下文)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved