VB怎么获取当前活动窗口的坐标? 如何获得vb中鼠标在窗口的坐标
代码如下。
=============
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Sub Form_Load()
Dim h As Long, r As RECT
h = FindWindow(vbNullString, "酷狗") '这里写上你的窗口标题,必须一字不差
GetWindowRect h, r
MsgBox "左上角坐标(" & r.Left & "," & r.Top & ")" & vbCrLf & "右下角坐标(" & r.Right & "," & r.Bottom & ")" & vbCrLf & "窗口高" & r.Bottom - r.Top & "窗口宽" & r.Right - r.Left
End
End Sub
方法一: 直接用 MouseDown事件
举例:(这种方法获取的是点的位置在窗体中,却该对象有MouseDown事件才行,其坐标值为所在容器的相对坐标值)
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = 1 Then
Cls
Print "X:"; X, "Y:"; Y
End If
End Sub
方法二:用API函数GetCursorPos来获取位置,用GetAsyncKeyState来获取是否按下左键
这种方法在任何时候都可以获取,哪怕鼠标不在应用程序内也行
在窗体上添加一个计时器,设置Interval属性为10
获取的位置的数字,是屏幕中的位置(不是相对窗体的)
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Type POINTAPI
X As Long
Y As Long
End Type
Private Sub Timer1_Timer()
Dim P As POINTAPI
X = GetAsyncKeyState(1)
If X = -32767 Then 'x返回的是16位整数,最高位为1,表明按下
Cls
Print "左键按下",
GetCursorPos P
Print " 鼠标x位置:" & P.X & " 鼠标y位置:" & P.Y
End If
X = GetAsyncKeyState(2)
If X = -32767 Then
Cls
Print "右键按下",
GetCursorPos P
Print " 鼠标x位置:" & P.X & " 鼠标y位置:" & P.Y
End If
End Sub
'把代码复制到Form1的代码窗口中
'获得活动窗口句柄的API
Private Declare Function GetForegroundWindow Lib "user32" () As Long
'获得窗口区域结构的API
Private Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, wndRect As RECT) As Long
Private Type RECT '自定义区域结构类型
x As Long
y As Long
Right As Long
Bottom As Long
End Type
Dim ActiveWindowRECT As RECT '用於保存活动窗口区域的结构
Dim ActiveWindowHwnd As Long '活动窗口的句柄
Private Sub Timer1_Timer()
ActiveWindowHwnd = GetForegroundWindow '获得活动窗口的句柄
GetWindowRect ActiveWindowHwnd, ActiveWindowRECT '获得活动窗口的区域并保存在 ActiveWindowRECT 变量中
'在窗口上输出信息
Me.Cls
Print "活动窗口的坐标是(" & ActiveWindowRECT.x & "," & ActiveWindowRECT.y & ")"
End Sub
'下面是代码,直接复制就行了
使用API
GetWindowsPos()