Search code examples
wpfmouse-coordinates

How do I get the current mouse screen coordinates in WPF?


How to get current mouse coordination on the screen? I know only Mouse.GetPosition() which get mousePosition of element, but I want to get the coordination without using element.


Solution

  • 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()
    {
        var 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()
    {
        var w32Mouse = new Win32Point();
        GetCursorPos(ref w32Mouse);
    
        return new Point(w32Mouse.X, w32Mouse.Y);
    }