FraserOfSmeg FraserOfSmeg - 1 year ago 111 Question

Mouse Events in

I'm trying to move the mouse while a 3rd party application (out of my control) is activated (the topmost program). Ideally I want to move the mouse relative to my current position, but using absolute positions wouldn't be hard to convert to. Here's what I currently use;

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

Public Sub MoveMouse(ByVal xPos As Long, ByVal yPos As Long)
mouse_event(MOUSEEVENTF_MOVE, xPos, yPos, 0, 0)
End Sub


It's called with;

MoveMouse(100, 100)

Now my problem is my mouse moves in y but not in x. I've tried some troubleshooting and it turns out the first value in the call (xPos) is actually the distance moved in y, not x. The yPos doesn't do anything.
For example the below code moves the mouse down by 50 pixels;

MoveMouse(50, 0)

What am I doing wrong?

Answer Source

Something must be wrong on your side because the following code does work:

Imports System.Runtime.InteropServices

Public Class Form1
    Public Const MOUSEEVENTF_MOVE = &H1

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

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dx = -10
        Dim dy = -10
        mouse_event(MOUSEEVENTF_MOVE, dx, dy, 0, 0)
    End Sub
End Class

Note that I slightly modified the signature of mouse_event to use Integer, since you cannot easily have a C# unchecked equivalent without having to specify the /removeintchecks option.

See if there's a program interfering with yours by closing them and trying again, if not then I'm afraid I can't suggest about another fix.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download