Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get mouse position on screen in WPF?

It works within a specific control, but it doesn't work out the specific control.

How to get mouse position and use mouse events independently of any control just directly from screen (without Platform Invoke)?

2 needed points:

  1. Mouse events when mouse is not within a control, but on a screen.
  2. Mouse position when mouse is not within a control, but on a screen.

It should be solved without using Platform Invoke.

Next two don't work:

System.Windows.Input.Mouse.GetPosition(this)

Doesn't get mouse position out a specific control.

System.Windows.Forms.Cursor.Position.X

System.Windows.Forms.Cursor.Position doesn't work because it has no types in a WPF app, but it works in a Windows Forms app.

IntelliSense gets System.Windows.Forms.Cursor.Position, but it doesn't get any type of Position, hence I can't get:

Position.X    
Position.Y

and

Point pointToWindow = Mouse.GetPosition(this);

Point pointToScreen = PointToScreen(pointToWindow);

Doesn't get mouse position out a specific control.

like image 910
Ziya Ceferov Avatar asked Apr 23 '15 11:04

Ziya Ceferov


2 Answers

Using MouseDown event of a control you can try this:

var point = e.GetPosition(this.YourControl);

EDIT: You can capture mouse event to a specific control using Mouse.Capture(YourControl); so it will capture the mouse events even if it is not on that control. Here is the link

like image 134
Hossein Narimani Rad Avatar answered Oct 01 '22 02:10

Hossein Narimani Rad


You can use PointToScreen

Converts a Point that represents the current coordinate system of the Visual into a Point in screen coordinates.

Something like this:

private void MouseCordinateMethod(object sender, MouseEventArgs e)
{
    var relativePosition = e.GetPosition(this);
    var point= PointToScreen(relativePosition);
    _x.HorizontalOffset = point.X;
    _x.VerticalOffset = point.Y;
}

Do note that Mouse.GetPosition returns a Point, and PointToScreen converts the point to the screen coordinate

EDIT:

You can use the Mouse.Capture(SepcificControl);. From MSDN

Captures mouse input to the specified element.

like image 31
Rahul Tripathi Avatar answered Oct 01 '22 01:10

Rahul Tripathi