Click here to Skip to main content
16,004,505 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
It works within a specific control, but it doesn't work out the specific control.

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 ones doesn't work:

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

Doesn't get mouse position out a specific control.

2.
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

3.
Point pointToWindow = Mouse.GetPosition(this);
Point pointToScreen = PointToScreen(pointToWindow);

Doesn't get mouse position out a specific control.
Posted
Updated 1-Aug-17 12:42pm
v15
Comments
Style-7 23-Apr-15 5:48am    
Use Cursor.Position

The next code gets Mouse Position relative to screen no matter where Mouse is:
C#
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        Label label = new Label();
        label.Width = 100;
        label.Height = 30;

        this.Content = label;

        this.Loaded += delegate
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Elapsed += delegate
            {
                this.Dispatcher.Invoke(new Action(delegate
                    {
                        Mouse.Capture(this);
                        Point pointToWindow = Mouse.GetPosition(this);
                        Point pointToScreen = PointToScreen(pointToWindow);
                        label.Content = pointToScreen.ToString();
                        Mouse.Capture(null);
                    }));
            };
            timer.Interval = 1;
            timer.Start();
        };
    }
}
 
Share this answer
 
v5
Hello,

You need to use Visual.PointToScreen

https://msdn.microsoft.com/en-us/library/system.windows.media.visual.pointtoscreen.aspx[^]

Point pointToWindow = Mouse.GetPosition(this);
Point pointToScreen = PointToScreen(pointToWindow);


Valery.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 23-Apr-15 1:06am    
Sure, a 5.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900