Win32 API 裡面定義了許多結構體,像是為了表達座標,於是定義了一個結構體叫 POINT。假設我們要調用 Win32 API 的 GetCursorPos - 取得現在 mouse 座標的函式,先看一下函式原型

BOOL WINAPI GetCursorPos(
  __out  LPPOINT lpPoint
);

看到這裡有個地方覺得怪怪的 - LPPOINT 是什麼?看一下 MSDN 的說明 - 

A pointer to a POINT structure that receives the screen coordinates of the cursor.

翻譯一下,事實上它是一個指標型態的 POINT 結構體 (正確的說法是指向 POINT 的指標,不過怕沒學過 C 語言所以這裡才這麼說)。重點部份紅色都標起來了。

--------------------------------------------------------------
// 結構體處理部份

之前我們有學過 autoit 結構體要怎麼去設定、調用,我們現在要做的就是先把那個 POINT 的結構體找出來,原型如下

typedef struct tagPOINT {
      LONG x;
      LONG y;
} POINT, *PPOINT;

嗯,好了,原來 POINT 這個結構體也只有二個成員,這二個成員都是 LONG,於是在 AutoIt 我們先為它建造一個結構體 POINT 出來

$struct_point = "LONG x;LONG y" ; 結構體 POINT
$current_point = DllStructCreate($struct_point)
If @error Then
 MsgBox(0, "", "DllStructCreate fail. " & @error)
EndIf

--------------------------------------------------------------
// autoit 呼叫、結構處理部份

 接下來就是呼叫了,這裡要注意,由於那個參數是  "pointer to " POINT,是指標型態,所以我們在傳入的時候,資料型態是給 "ptr",至於變數不是給 $current_point,而是要經過一點處理 - DllStructGetPtr($current_point),轉成指標型態再傳進去,原型碼參考下面

$Result = DllCall("user32.dll", "BOOL", "GetCursorPos", _
                   "ptr", _
; 由於是 "pointer to something", 指標, 所以輸入的資料型態為 "ptr"
                    DllStructGetPtr($current_point)) ; 取得結構體 $current_point 的指標,當作是傳入的變數

 

--------------------------------------------------------------
// 取出結果

一般的資料型態我們都是從 $Result[0]、 $Result[1]... 這樣去取得它的結果。這裡的結果是放在第一個引數,所以用 $Result[0]?很抱歉,這是錯的。我們在上幾篇文章有提到,要讀取結構體的內容,是用 DllStructGetData 方式,所以要讀的話是這麼做


$X = DllStructGetData($current_point, "x")
$Y = DllStructGetData($current_point, "y")
MsgBox(0, "", "x=" & $X)
MsgBox(0, "", "Y=" & $Y)

嗯,這些全部都有了,下面便是完整程式碼

$struct_point = "LONG x;LONG y" ; 結構體 POINT
$current_point = DllStructCreate($struct_point)
If @error Then
 MsgBox(0, "", "DllStructCreate fail. " & @error)
EndIf

$Result = DllCall("user32.dll", "BOOL", "GetCursorPos", _
                   "ptr", _
; 由於是 "pointer to something", 指標, 所以輸入的資料型態為 "ptr"
                    DllStructGetPtr($current_point)) ; 取得結構體 $current_point 的指標,當作是傳入的變數

$X = DllStructGetData($current_point, "x")
$Y = DllStructGetData($current_point, "y")
MsgBox(0, "", "x=" & $X)
MsgBox(0, "", "Y=" & $Y)

arrow
arrow
    全站熱搜

    edisonx 發表在 痞客邦 留言(0) 人氣()