ck_
ck_

Reputation: 3829

Why won't my mouse cursor move where I tell it to go with Cursor.Position?

I'm doing some manipulation of the mouse cursor regarding clipping areas, and to this end I need to show a "fake" cursor on the screen. My real cursor will eventually be hidden, and just slightly off from the user's fake cursor to give me a buffer to preform clipping operations. But that's not really important.

This is so weird. It seems like the program is blatantly ignoring my commands. I have some debug code:

Debug.WriteLine("1fake: " + fakeMouse.X + " " + fakeMouse.Y);
Debug.WriteLine("1real: " + this.PointToClient(Cursor.Position).X + " " + this.PointToClient(Cursor.Position).Y);

int fmx = fakeMouse.X;
int fmy = fakeMouse.Y;

Cursor.Position = new Point(fmx, fmy);

Debug.WriteLine("2fake: " + fmx + " " + fmy);
Debug.WriteLine("2real: " + this.PointToClient(Cursor.Position).X + " " + this.PointToClient(Cursor.Position).Y);

And this results in debugger output like this:

1fake: 489 497
1real: 490 500
2fake: 489 497
2real: 274 264 // I just set this to be EXACTLY The same as the value above it!?!

The cursor jumps way out of the way, into a completely different part of the screen. I did the fmx, fmy things to just reduce the problem to pure integer coordinates but it's still not taking the right parameters. Is it somehow being changed again somewhere else? I don't understand.

Upvotes: 1

Views: 731

Answers (2)

Stilgar
Stilgar

Reputation: 23611

This is because you are using PointToClient before writing the output. The cursor position is relative to the screen and not to your form

Upvotes: 1

Tim Sylvester
Tim Sylvester

Reputation: 23168

Cursor.Position expects a point in screen coordinates. If your point is in window or client coordinates it will be offset from where you expect.

You probably just need to call PointToScreen. Something like:

Cursor.Position = this.PointToScreen(new Point(fakeMouse.X, fakeMouse.Y));

http://msdn.microsoft.com/en-us/library/ms229598.aspx

Upvotes: 2

Related Questions