How to get mouse position on screen in WPF?
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.
I have little new found,
Code is below, fisrt build and run the Window ,
then just wheel your mouse one time on the window to invoke the endless screen detect of the Mouse Position.
(Thus I didn't find the way to detect mouse event out of the control in the second point of the question, but similar use an endless thread.)
But I just use a little skill to enable Windows.Forms in WPF Project, by simply use the Forms code in pure method, then refer that method in the Event Code Block.
.
Here's the Code:
Add two references to project:
System.Drawing
System.Windows.Forms
Xaml part:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:g="clr-namespace:Gma.UserActivityMonitor;assembly=Gma.UserActivityMonitor"
Title="MainWindow" Height="350" Width="525"
MouseWheel="MainWindow_OnMouseWheel">
<Grid>
<TextBlock Name="TBK" />
</Grid>
</Window>
Class Code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void KeepReportMousePos()
{
//Endless Report Mouse position
Task.Factory.StartNew(() =>
{
while(true){
this.Dispatcher.Invoke(
DispatcherPriority.SystemIdle,
new Action(() =>
{
GetCursorPos();
}));
}
});
}
public void GetCursorPos()
{
//get the mouse position and show on the TextBlock
System.Drawing.Point p = System.Windows.Forms.Cursor.Position;
TBK.Text = p.X + " " + p.Y;
}
private void MainWindow_OnMouseWheel(object sender, MouseWheelEventArgs e)
{
//invoke mouse position detect when wheel the mouse
KeepReportMousePos();
}
}
Why complicate things? Just pass null
to get screen coordinates:
private void MouseCordinateMethod(object sender, MouseEventArgs e)
{
var screenPos = e.GetPosition(null);
// ...
}
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