Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 663
Prince OfThief Avatar asked Nov 19 '10 15:11

Prince OfThief


People also ask

Which function is used to send the cursor to the specified coordinates in the active window?

The moveTo() method moves a window to the specified coordinates.

How do I find my mouse coordinates in Python?

To determine the mouse's current position, we use the statement, pyautogui. position(). This function returns a tuple of the position of the mouse's cursor. The first value is the x-coordinate of where the mouse cursor is.


2 Answers

Or in pure WPF use PointToScreen.

Sample helper method:

// Gets the absolute mouse position, relative to screen Point GetMousePos() => _window.PointToScreen(Mouse.GetPosition(_window)); 
like image 196
erikH Avatar answered Sep 30 '22 12:09

erikH


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); } 
like image 45
Fredrik Hedblad Avatar answered Sep 30 '22 11:09

Fredrik Hedblad