首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 調用 WinAPI:GetCursorPos 與螢幕/用戶端座標轉換

     編輯:Delphi

滑鼠座標系統完全指南:螢幕 ↔ 用戶端區域

Windows 使用兩種座標系:螢幕座標 (以螢幕左上角為原點) 與 用戶端座標 (以視窗用戶端區域左上角為原點)。GetCursorPos 取得螢幕座標,VCL 提供 ScreenToClient / ClientToScreen 方法互轉,亦可直接呼叫同名 API 函數。

四種常見取得/轉換方式

1. 直接用事件參數 (已是用戶端座標)


procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  str: string;
begin
  str := Format('%d,%d', [X, Y]);
  ShowMessage(str);
end;

2. GetCursorPos 取得螢幕座標


var
  ps: TPoint;
  str: string;
begin
  GetCursorPos(ps);
  str := Format('%d,%d', [ps.X, ps.Y]);
  ShowMessage(str);
end;

3. 螢幕座標 → 用戶端座標 (ScreenToClient)


var
  ps: TPoint;
  str: string;
begin
  GetCursorPos(ps);
  ps := ScreenToClient(ps); // TWinControl 方法
  str := Format('%d,%d', [ps.X, ps.Y]);
  ShowMessage(str);
end;

4. 用戶端座標 → 螢幕座標 (ClientToScreen)


procedure TForm1.FormMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  str: string;
  ps: TPoint;
begin
  str := Format('%d,%d', [X, Y]); // 用戶端座標
  ShowMessage(str);

  ps := Point(X, Y);
  ps := ClientToScreen(ps); // 轉螢幕座標
  str := Format('%d,%d', [ps.X, ps.Y]);
  ShowMessage(str);
end;

API 版本對應

VCL 方法WinAPI 函數用途
ScreenToClientScreenToClient(hWnd, lpPoint)螢幕 → 用戶端
ClientToScreenClientToScreen(hWnd, lpPoint)用戶端 → 螢幕
-GetCursorPos(lpPoint)取得螢幕座標

掌握座標轉換,拖放、ToolTip 定位、跨視窗互動才能得心應手。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved