Set Mouseposition in WPF
Solution 1
You can use the Cursor.Position
property found in System.Windows.Forms
for this.
As demonstrated on the MSDN documentation for Cursor.Position
:
private void MoveCursor()
{
// Set the Current cursor, move the cursor's Position,
// and set its clipping rectangle to the form.
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}
If you're looking to do this outside of Windows Forms, you can do a platform invoke on User32's SetCursorPos.
Solution 2
It is not possible using the .NET BCL. However if you really want it you can use native SetCursorPos
in User32.dll
.
[DllImport("User32.dll")]
private static extern bool SetCursorPos(int x, int y);
As others will most likely point out, you can achieve the same using System.Windows.Forms
, however when developing a WPF application prefer use DllImport
.
If you are going use the Kinect sensor in your application I would personally write a custom WPF control than trying to override the system mouse as:
- You have to think carefully about showing user intent with the Kinect, e.g., to select an option you would have the user hover over the button and display a timer before actioning.
- You want to have a custom visual to represent the location on screen, the traditional cursor is not enough.
At the X360 Kinect conference that I went to earlier this year, almost half the day was dedicated to managing the user experience as it is that different from a simple point-and-click interaction.
If you are interested, I can upload/e-mail the slides from the Kinect conference. They are a good read.
Tom Kerkhove
Azure Consultant @ Codit & Microsoft MVP for Microsoft Azure.
Updated on June 04, 2022Comments
-
Tom Kerkhove almost 2 years
I'm going to replace my mouse by Kinect gestures but I can't find a way to set mouseposition for a WPF app.
-
Xcalibur37 over 12 yearsYou have a good idea there, but typically WPF apps should stay away from System.Windows.Forms if possible.
-
Xcalibur37 over 12 yearsDid more research on it. You are correct. It doesn't look like there is a more graceful way to do other than the 2 methods you suggested. +1 for you on that one.
-
Krythic over 7 yearsWould recommend wrapping this in a function that way you're not mixing WPF with Winforms and clashing namespaces.