如何处理用户在表单外单击鼠标?

时间:2013-12-08 03:47:30

标签: vb.net

我正在VB.NET中创建一个项目,我们在屏幕上的任何位置跟踪光标的位置 在Timer 1_ Tick事件中,我将频率设置为1毫秒,以便它可以更频繁地跟踪位置。以下是我在Timer1_Tick事件中插入的代码

    Me.Cursor = New Cursor(Cursor.Current.Handle)
    Label4.Text = Cursor.Position.X
    Label5.Text = Cursor.Position.Y

我希望用户在表单外部单击并拖动以获取所选区域的尺寸(以像素为单位)。任何人都可以帮助如何控制鼠标在表单外单击?

提前致谢!

1 个答案:

答案 0 :(得分:2)

听起来您正试图从应用程序外部获取一个区域,您可以尝试使用Global Hook,例如可从此CodePlex Project获得。

这是一个简单的例子,它响应MouseDown和MouseUp事件创建一个Rectangle,然后将结果打印到TextBox,它应该让你知道如何继续。

Imports MouseKeyboardActivityMonitor
Imports MouseKeyboardActivityMonitor.WinApi

Public Class Form1
    Private m_MouseHookManager As MouseHookListener
    Dim tempPoint As Point

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        m_MouseHookManager = New MouseHookListener(New GlobalHooker)
        m_MouseHookManager.Enabled = True
        AddHandler m_MouseHookManager.MouseUp, AddressOf HookManager_MouseUp
        AddHandler m_MouseHookManager.MouseDown, AddressOf HookManager_MouseDown
        TextBox1.ScrollBars = ScrollBars.Vertical
    End Sub

    Private Sub HookManager_MouseUp(sender As Object, e As MouseEventArgs)
        Dim r As Rectangle = New Rectangle(tempPoint.X, tempPoint.Y, e.X - tempPoint.X, e.Y - tempPoint.Y)
        TextBox1.Text += "Left: " & r.Left & vbCrLf
        TextBox1.Text += "Right: " & r.Top & vbCrLf
        TextBox1.Text += "Width: " & r.Width & vbCrLf
        TextBox1.Text += "Height: " & r.Height & vbCrLf
        tempPoint = Point.Empty
    End Sub


    Private Sub HookManager_MouseDown(sender As Object, e As MouseEventArgs)
        tempPoint = e.Location
    End Sub
End Class