鼠标事件轮最后发生

时间:2017-08-04 16:08:19

标签: vb.net

我的应用程序中发生了一些奇怪的事情,我无法弄清楚它是什么。我正在尝试模拟鼠标单击并以编程方式滚动。

我可以成功执行鼠标单击并以编程方式滚动,但问题是鼠标滚轮最后出现。

这是代码:

 <DllImport("user32.dll", EntryPoint:="mouse_event")>
    Private Shared Sub mouse_event(ByVal dwFlags As UInteger, ByVal dx As
    Integer, ByVal dy As Integer, ByVal dwData As Integer, ByVal dwExtraInfo
    As UInteger)
End Sub

标志:

Const MOUSEEVENTF_LEFTDOWN As UInteger = &H2 '0x0002'
Const MOUSEEVENTF_LEFTUP As UInteger = &H4 '0x0004'
Const MOUSEEVENTF_WHEEL As UInteger = &H800
Const MOUSEEVENTF_XDOWN As UInteger = &H80


Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    scroll_to_end()
    Thread.Sleep(300)
    click_perf()

    MessageBox.Show("S")
End Sub
Private Sub scroll_to_end()
    'Focus panel1'

    c_point = New Point(Panel1.Location.X + 1, Panel1.Location.Y + 1)
    Cursor.Position = Me.PointToScreen(c_point)
    mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
    'Wait'
    Thread.Sleep(150)

    'Scroll to the end of the page'
    Dim scroll_down As Integer = -(10 * 120) 'Perform 10 scrolls down'
    mouse_event(MOUSEEVENTF_WHEEL, 0, 0, scroll_down, 0)

   'This is the fix:'
   Application.DoEvents()
End Sub
Private Sub click_perf()
    'Move mouse diagonally 200px'

    c_point.X += 200
    c_point.Y += 200
    Cursor.Position = Me.PointToScreen(c_point)

    'Perform click'
    mouse_event(MOUSEEVENTF_LEFTDOWN, c_point.X, c_point.Y, 0, 0)
    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
End Sub

当我点击button3时,我想要关注panel1然后滚动到最后并向下对角移动鼠标200px,然后模拟点击。

实际发生的事情:鼠标移动到panel1,模拟鼠标按钮和鼠标按钮。然后,它将鼠标对角移动200px并显示消息框。滚动甚至没有发生,现在当我关闭消息框面板1时可能会失去焦点并且不会滚动。

如果我删除了messagebox.show(&#34;&#34;):鼠标移动到panel1并像上面那样对焦。它滚动到最后,但它在向下滚动之前执行单击。

修改 要解决此问题,我们需要在WHEEL MOUSE EVENT之后放置Application.DoEvents()

1 个答案:

答案 0 :(得分:1)

在每个UI操作之后放置它以强制它按顺序发生

for (int num = 0; num <= 100; num++) {
    for (int j = 2; j < num; j++) {
        if (num % j == 0) {
            System.out.println(num + " is not a prime number.");
            break;
        }
        if (num - j == 1) {
            System.out.println("PRIME NUMBER FOUND! It's: " + num + ".");
            myPrimeNumbers.add(num);
        }
    }
}

UI事件在message loop中处理,它查看消息队列并处理它们。如果它们在代码中大约同时被引发,则无法保证它们将按照它们被引发的顺序进行处理,因为您的代码比循环更快。 Application.DoEvents()将暂停代码执行并强制循环处理所有挂起的消息,从而使它们按顺序发生。

然而,由于其广泛滥用,通常认为使用这种方法的做法很差。我认为你的情况很好,也许是我唯一见过的。

我有兴趣看看是否有人可以提供首选替代方案......