**To Answer your first question**
Here are two ways in which you can get Mouse Screen Coordinates in WPF.
1.Using Windows Forms. Add a reference to System.Windows.Forms
public static Point GetMousePositionWindowsForms()
{
System.Drawing.Point point = Control.MousePosition;
return new Point(point.X, point.Y);
}
2.Using Win32
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
public static Point GetMousePosition()
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
**Note**:
You can use Window.Deactivated Event to detect the mouse click out of bound of the Window.
Window w = new Window();
w.Show();
w.Deactivated += (sender, args) =>
{
// When the user clicks outside your window, this event will be fired.
// Call the etMousePosition() here
Point point = GetMousePosition();
//Continue to position the mouse at a specified point.
};
**update**
In some case, if you can not get the mouse position by this method, you can try to run a thread, and listen for the mouse position for a fixed time interval.
using System.Runtime.InteropServices;
using Point = System.Drawing.Point;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetCursorPos(ref Point lpPoint);
public Form1()
{
InitializeComponent();
new Thread(() =>
{
while (true)
{
//Logic
Point p = new Point();
GetCursorPos(ref p);
//Decide here, that your mouse position is within your window boundary.
//If outside your window boundary, continue to position the mouse at a specified point.
Thread.Sleep(1000);
}
}).Start();
}
}
**To Answer your second question**
same as before, DllImport the user32.dll
[DllImport("User32.dll")]
private static extern bool SetCursorPos(int X, int Y);
and use the following system call, when your condition was met. Refer the above answer.
SetCursor(200, 200);
To follow up on Rachel's answer.
Here's two ways in which you can get Mouse Screen Coordinates in WPF.
1.Using Windows Forms. Add a reference to System.Windows.Forms
public static Point GetMousePositionWindowsForms()
{
System.Drawing.Point point = Control.MousePosition;
return new Point(point.X, point.Y);
}
2.Using Win32
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
public static Point GetMousePosition()
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}