采用窗体的MouseMove事件来获取鼠标坐标是可以的。如下我在文本框中显示当前鼠标的坐标程序,鼠标移动,坐标自动更新,只需要一个文本框控件,代码如下:Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Text1.Text = "当前鼠标坐标为,X:" & X & "Y:" & Y
End Sub
在VB中针对Form、Text文本输入框等都有关于鼠标的三个函数:,_MouseDown、_MouseMove、_MouseUp,如:关于Form有如下三个函数,只要在其中写入针对Timer控件的语句即可,无需理会坐标X、Y的值。 Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) End Sub Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) End Sub Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) End Sub
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
TextBox1.Text = e.X.ToString
TextBox2.Text = e.Y.ToString
End Sub
MouseMove对一些控件无法支持,如WEB控件,鼠标坐标会获取失败,还是API好用一些
(vb.net 2010的代码)代码如下
Private Declare Function GetCursorPos Lib "user32" (ByRef lpPoint As POINTAPI) As Long '全屏坐标声明
Private Declare Function ScreenToClient Lib "user32.dll" (ByVal hwnd As Int32, ByRef lpPoint As POINTAPI) As Int32 '窗口坐标声明
Private Structure POINTAPI '声明坐标变量
Public x As Int32 '声明坐标变量为32位
Public y As Int32 '声明坐标变量为32位
End Structure
'以上是声明部分
'以下是窗口部分
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick '用时钟控件来取坐标,窗口上放个Timer组件,Enabled为允许,周期为10到100毫秒均可
Dim P As POINTAPI '声明坐标变量
Dim xx, yy '声明转换要用到的变量
GetCursorPos(P) '获取鼠标在屏幕中的位置
ScreenToClient(Me.Handle.ToInt32, P) '转换为本窗体的坐标
xx = P.x.ToString '把X转换成能显示到文本框的字符串格式
yy = P.y.ToString '把Y转换成能显示到文本框的字符串格式
TextBox1.Text = xx + "和" + yy '文本框的内容为X坐标和Y坐标
End Sub
VB6代码如下:
Private Type POINT'声明坐标变量类
x As Long '声明坐标变量
y As Long '声明坐标变量
End Type
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINT) As Long'全屏坐标函数声明
Private Declare Function ScreenToClient Lib "user32" (ByVal hwnd As Long, lpPoint As POINT) As Long'用户窗口坐标函数声明
'以上是声明部分
'以下是窗口部分
Private Sub Timer1_Timer()'用时钟控件来取坐标,窗口上放个Timer组件,Enabled为允许,周期为10到100毫秒均可
Dim P As POINT '声明坐标变量
GetCursorPos P'获取鼠标在屏幕中的位置
ScreenToClient Me.hwnd, P '获取鼠标在窗口中的位置
Text1.Text = xx + "和" + yy '文本框的内容为本窗口X坐标和Y坐标
End Sub