2011年12月26日月曜日

[ExcelVBA] GetWindowRect

 
■説明
ウィンドウ全体の座標を取得する関数

■宣言
Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long
第一引数:ウィンドウのハンドルを指定
第二引数:ウィンドウのtop/right/bottom/leftの値を格納するための構造体を指定します
例)
  1. Type RECT  
  2. Left As Long  
  3. Top As Long  
  4. Right As Long  
  5. Bottom As Long  
  6. End Type  
戻り値:失敗した時0を返します

■サンプルコード
では、サンプルとして、デスクトップのサイズを大きさを出してみます。
デスクトップのハンドルを取得するには、 GetDesktopWindow関数を使用すれば取得できます。
GetDesktopWindow関数について
  1. Option Explicit  
  2.   
  3. Declare Function GetDesktopWindow Lib "user32" () As Long  
  4.   
  5. Sub SampleCode1()  
  6.     Dim hwnd As Long  
  7.     hwnd = GetDesktopWindow()  
  8.       
  9.     Debug.Print hwnd  
  10. End Sub  
説明するまでもない簡単なコードです。
ただし、ウィンドウのハンドルがわかっただけでは、うれしくもないので
他の関数に渡して活用してみます。
  1. Option Explicit  
  2.   
  3. Declare Function GetDesktopWindow Lib "user32" () As Long  
  4. Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long  
  5.   
  6. Type RECT  
  7.     Left As Long  
  8.     Top As Long  
  9.     Right As Long  
  10.     Bottom As Long  
  11. End Type  
  12.   
  13. Sub SampleCode()  
  14.     Dim hwnd As Long  
  15.     hwnd = GetDesktopWindow()  
  16.       
  17.     Dim Re As RECT  
  18.     Dim Result As Long  
  19.     Result = GetWindowRect(hwnd, Re)  
  20.       
  21.     Debug.Print "左上(x, y) = (" & Re.Left & ", " & Re.Top & ")"  
  22.     Debug.Print "右下(x, y) = (" & Re.Right & ", " & Re.Bottom & ")"  
  23.       
  24.     Debug.Print "Width :" & (Re.Right - Re.Left)  
  25.     Debug.Print "Heihgt:" & (Re.Bottom - Re.Top)  
  26. End Sub  
実行結果例:
左上(x, y) = (0, 0)
右下(x, y) = (1920, 1080)
Width :1920
Heihgt:1080

今度は、電卓を起動して、電卓のウィンドウ座標を取得してみます。
  1. Option Explicit  
  2.   
  3. Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long  
  4. Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" _  
  5.     (ByVal lpClassName As StringByVal lpWindowName As StringAs Long  
  6.   
  7. Type RECT  
  8.     Left As Long  
  9.     Top As Long  
  10.     Right As Long  
  11.     Bottom As Long  
  12. End Type  
  13.   
  14. Sub SampleCode()  
  15.     Dim hwnd As Long  
  16.     hwnd = FindWindow("SciCalc""電卓")  
  17.       
  18.     Dim Re As RECT  
  19.     Dim Result As Long  
  20.     Result = GetWindowRect(hwnd, Re)  
  21.       
  22.     Debug.Print "左上(x, y) = (" & Re.Left & ", " & Re.Top & ")"  
  23.     Debug.Print "右下(x, y) = (" & Re.Right & ", " & Re.Bottom & ")"  
  24.       
  25.     Debug.Print "Width :" & (Re.Right - Re.Left)  
  26.     Debug.Print "Heihgt:" & (Re.Bottom - Re.Top)  
  27. End Sub  
実行結果例:
 左上(x, y) = (66, 87)
 右下(x, y) = (368, 332)
 Width :302
 Heihgt:245


 今度は、関数電卓モードに切り替えて実行してみます。
 左上(x, y) = (66, 87)
 右下(x, y) = (625, 384)
 Width :559
 Heihgt:297
 

0 件のコメント: