C # reliable MouseMove (hop)

I use this function to move the cursor.

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

When I use a hotkey to launch it, the cursor will move to the correct coordinates, and the next time I move the mouse, it will continue from that position. Designated work.

However, I need to run SetCursorPos during the MouseMove event. If the user moves the mouse to a specific area, I want her to jump to another location and continue from there. But now he jumps to his destination, and then immediately returns back (90% of the time). How can I avoid this behavior?

Edit: I decided to get around this by cutting off the cursor in a 1 by 1 pixel square for the 1 mousemove event. Cursor.Clip (MousePosition, new rectangle (1, 1));

+7
source share
2 answers

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

For example, here I added a green 200x200 panel at position 0, 0 in the upper left corner. If the mouse moves around the panel, the MouseMove form MouseMove will no longer capture the position of the mouse cursor. In my mouse_move form event, I set the form text to display the coordinates of the mouse. Please note that the coordinates in the window text are still 200, 200 when the mouse was actually at 0, 0 (my cursor cannot see due to the need to click on SnippingTool.exe to get a screenshot).

enter image description here

To fix this, use the same code that you posted on the MouseMove event form in the MouseMove event panel (or whatever control you use). This results in the correct coordinates in the form text.

enter image description here

And here is the code (this, obviously, can be reorganized into one 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}", eX, eY); if (eX >= 0 && eX <= 200) { if (eY >= 0 && eY <= 200) { SetCursorPos(500, 500); } } } private void panel1_MouseMove(object sender, MouseEventArgs e) { this.Text = string.Format("X: {0}, Y: {1}", eX, eY); if (eX >= 0 && eX <= 200) { if (eY >= 0 && eY <= 200) { SetCursorPos(500, 500); } } } } 
+1
source

It's hard to say with such little information (maybe a screenshot of your GUI will help). You can try:

  private void Button_MouseMove_1(object sender, MouseEventArgs e) { SetCursorPos(0, 0); e.Handled = true; } 
0
source

All Articles