Mouse.GetPosition Method
Gets the position of the mouse relative to a specified element.
Assembly: PresentationCore (in PresentationCore.dll)
Parameters
- relativeTo
- Type: System.Windows.IInputElement
The coordinate space in which to calculate the position of the mouse.
Return Value
Type: System.Windows.PointThe position of the mouse relative to the parameter relativeTo.
The position of the mouse pointer is calculated relative to the specified element with the upper-left corner of element being the point of origin, 0,0.
During drag-and-drop operations, the position of the mouse cannot be reliably determined through GetPosition. This is because control of the mouse (possibly including capture) is held by the originating element of the drag until the drop is completed, with much of the behavior controlled by underlying Win32 calls. Try the following approaches instead:
-
Call the GetPosition method of the DragEventArgs that is passed to the drag events (DragEnter, DragOver, DragLeave).
-
Call GetCursorPos, using P/Invoke.
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
public static class MouseUtils
{
//do not use while DoDragDrop is happening
public static Point GetMouseAbsoluteScreenPosition(this UIElement visual)
{
return visual.PointToScreen(Mouse.GetPosition(visual));
}//use like that: this.GetMouseAbsoluteScreenPosition();
//use in conjunction with PreviewGiveFeedback to simulate MouseMove event
public static Point GetMouseAbsoluteScreenPositionNative()
{
Win32Point point;
if (!GetCursorPos(out point))
{
var e = Marshal.GetLastWin32Error();
throw new Win32Exception(e);
}
return point;
}
//get mouse position , on drag & drop, Mouse.GetPosition Doesn't work when doing DragDrop.DoDragDrop()
//http://www.switchonthecode.com/tutorials/wpf-snippet-reliably-getting-the-mouse-position
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms648390(v=vs.85).aspx
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", EntryPoint = "GetCursorPos", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
private static extern bool ([Out] out Win32Point lpPoint);
//http://msdn.microsoft.com/en-us/library/windows/desktop/dd162805(v=vs.85).aspx
[StructLayout(LayoutKind.Sequential)]
private struct Win32Point
{
public int x;//not readonly because of out parameter
public int y;//not readonly because of out parameter
public Win32Point(int x, int y)
{
this.x = x;
this.y = y;
}
public override string ToString()
{
return (x + "," + y);
}
public static implicit operator Point(Win32Point p)
{
return new Point(p.x, p.y);
}
public static implicit operator Win32Point(Point p)
{
return new Win32Point((int)p.X, (int)p.Y);
}
}
}
- 12/27/2011
- igalk474