7

I'm using this function to move the cursor.

[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);

When I use a hotkey to trigger it, the cursor will move to the correct coords and next time I move the mouse it continues from that position. Working as intended.

However I need to trigger SetCursorPos during a MouseMove event. If user moves mouse into a certain area I want it to hop to a different place and carry on from there. But right now it hops to the destination and then immediately hops back (90% of the time). How can I avoid that behavior?

Edit: I decided to work around it by clipping the cursor in 1 by 1 px square for 1 mousemove event. Cursor.Clip(MousePosition, new Rectangle(1, 1));

user1340531
  • 720
  • 1
  • 10
  • 21

2 Answers2

1

My guess is that there is another control on top of your form in the area where you want to trigger the event. If so, the control is capturing the MouseMove event.

For example, here I've added a green 200x200 panel at position 0, 0 in the upper left hand corner. If the mouse moves over the panel, the form's MouseMove event will stop capturing the mouse cursor position. In my form's mouse_move event, I set the form's text to display the mouse coordinates. Notice the coordinates in the Window Text are still 200, 200 when the mouse was actually at 0, 0 (can't see my cursor due to having to click on SnippingTool.exe to get the screenshot).

enter image description here

To remedy this, use the same code you placed in your form's MouseMove event in the panel's MouseMove event (or whichever control you are using). This results in the correct coordinates in the form's text.

enter image description here

And here is the code (This could obviously be refactored into a single method):

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    static extern bool SetCursorPos(int X, int Y);

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        this.Text = string.Format("X: {0}, Y: {1}", e.X, e.Y);

        if (e.X >= 0 && e.X <= 200)
        {
            if (e.Y >= 0 && e.Y <= 200)
            {
                SetCursorPos(500, 500);
            }
        }
    }

    private void panel1_MouseMove(object sender, MouseEventArgs e)
    {
        this.Text = string.Format("X: {0}, Y: {1}", e.X, e.Y);

        if (e.X >= 0 && e.X <= 200)
        {
            if (e.Y >= 0 && e.Y <= 200)
            {
                SetCursorPos(500, 500);
            }
        }
    }
}
Inisheer
  • 20,376
  • 9
  • 50
  • 82
0

Hard to say with such little Information (maybe a screenshot of your GUI would help). You could try:

    private void Button_MouseMove_1(object sender, MouseEventArgs e)
    {
        SetCursorPos(0, 0);
        e.Handled = true;
    }
Pharap
  • 3,826
  • 5
  • 37
  • 51
Stefan
  • 528
  • 4
  • 12