如何在WPF中获得当前的鼠标屏幕坐标?

时间:2022-11-25 14:50:38

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.

如何在屏幕上获得当前鼠标的协调?我只知道Mouse.GetPosition()获取元素的mousePosition,但是我想在不使用元素的情况下获得协调。

6 个解决方案

#1


56  

To follow up on Rachel's answer.
Here's two ways in which you can get Mouse Screen Coordinates in WPF.

跟进瑞秋的回答。这里有两种方法可以在WPF中获得鼠标屏幕坐标。

1.Using Windows Forms. Add a reference to System.Windows.Forms

1。使用Windows窗体。添加对System.Windows.Forms的引用

public static Point GetMousePositionWindowsForms()
{
    System.Drawing.Point point = Control.MousePosition;
    return new Point(point.X, point.Y);
}

2.Using Win32

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

#2


52  

Or in pure WPF use PointToScreen.

或者在纯WPF中使用PointToScreen。

Sample helper method:

示例辅助方法:

// Gets the absolute mouse position, relative to screen
Point GetMousePos(){
    return _window.PointToScreen(Mouse.GetPosition(_window))
}

#3


23  

Do you want coordinates relative to the screen or the application?

您想要相对于屏幕或应用程序的坐标吗?

If it's within the application just use:

如果在应用程序中,请使用:

Mouse.GetPosition(Application.Current.MainWindow);

If not, I believe you can add a reference to System.Windows.Forms and use:

如果没有,我相信您可以添加一个对System.Windows的引用。形式和使用:

System.Windows.Forms.Control.MousePosition;

#4


13  

If you try a lot of these answers out on different resolutions, computers with multiple monitors, etc. you may find that they don't work reliably. This is because you need to use a transform to get the mouse position relative to the current screen, not the entire viewing area which consists of all your monitors. Something like this...(where "this" is a WPF window).

如果你在不同的分辨率、多显示器等电脑上尝试了很多这样的答案,你会发现它们并不可靠。这是因为您需要使用转换来获得鼠标相对于当前屏幕的位置,而不是包含所有监视器的整个查看区域。是这样的……(其中“this”是WPF窗口)。

var transform = PresentationSource.FromVisual(this).CompositionTarget.TransformFromDevice;
var mouse = transform.Transform(GetMousePosition());

public System.Windows.Point GetMousePosition()
{
    System.Drawing.Point point = System.Windows.Forms.Control.MousePosition;
    return new System.Windows.Point(point.X, point.Y);
}

#5


2  

This works without having to use forms or import any DLLs:

这无需使用表单或导入任何dll:

   using System.Windows;
   using System.Windows.Input;

    /// <summary>
    /// Gets the current mouse position on screen
    /// </summary>
    private Point GetMousePosition()
    {
        // Position of the mouse relative to the window
        var position = Mouse.GetPosition(Window);

        // Add the window position
        return new Point(position.X + Window.Left, position.Y + Window.Top);
    }

#6


0  

You may use combination of TimerDispatcher (WPF Timer analog) and Windows "Hooks" to catch cursor position from operational system.

您可以使用TimerDispatcher (WPF计时器模拟)和Windows“钩子”组合来捕获操作系统中的游标位置。

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetCursorPos(out POINT pPoint);

Point is a light struct. It contains only X, Y fields.

Point是一个轻结构体。它只包含X Y字段。

    public MainWindow()
    {
        InitializeComponent();

        DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
        dt.Tick += new EventHandler(timer_tick);
        dt.Interval = new TimeSpan(0,0,0,0, 50);
        dt.Start();
    }

    private void timer_tick(object sender, EventArgs e)
    {
        POINT pnt;
        GetCursorPos(out pnt);
        current_x_box.Text = (pnt.X).ToString();
        current_y_box.Text = (pnt.Y).ToString();
    }

    public struct POINT
    {
        public int X;
        public int Y;

        public POINT(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }

This solution is also resolving the problem with too often or too infrequent parameter reading so you can adjust it by yourself. But remember about WPF method overload with one arg which is representing ticks not milliseconds.

该解决方案还解决了参数读取频率过高或过低的问题,因此您可以自己调整它。但是请记住WPF方法重载,使用一个arg表示节拍,而不是毫秒。

TimeSpan(50); //ticks

#1


56  

To follow up on Rachel's answer.
Here's two ways in which you can get Mouse Screen Coordinates in WPF.

跟进瑞秋的回答。这里有两种方法可以在WPF中获得鼠标屏幕坐标。

1.Using Windows Forms. Add a reference to System.Windows.Forms

1。使用Windows窗体。添加对System.Windows.Forms的引用

public static Point GetMousePositionWindowsForms()
{
    System.Drawing.Point point = Control.MousePosition;
    return new Point(point.X, point.Y);
}

2.Using Win32

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

#2


52  

Or in pure WPF use PointToScreen.

或者在纯WPF中使用PointToScreen。

Sample helper method:

示例辅助方法:

// Gets the absolute mouse position, relative to screen
Point GetMousePos(){
    return _window.PointToScreen(Mouse.GetPosition(_window))
}

#3


23  

Do you want coordinates relative to the screen or the application?

您想要相对于屏幕或应用程序的坐标吗?

If it's within the application just use:

如果在应用程序中,请使用:

Mouse.GetPosition(Application.Current.MainWindow);

If not, I believe you can add a reference to System.Windows.Forms and use:

如果没有,我相信您可以添加一个对System.Windows的引用。形式和使用:

System.Windows.Forms.Control.MousePosition;

#4


13  

If you try a lot of these answers out on different resolutions, computers with multiple monitors, etc. you may find that they don't work reliably. This is because you need to use a transform to get the mouse position relative to the current screen, not the entire viewing area which consists of all your monitors. Something like this...(where "this" is a WPF window).

如果你在不同的分辨率、多显示器等电脑上尝试了很多这样的答案,你会发现它们并不可靠。这是因为您需要使用转换来获得鼠标相对于当前屏幕的位置,而不是包含所有监视器的整个查看区域。是这样的……(其中“this”是WPF窗口)。

var transform = PresentationSource.FromVisual(this).CompositionTarget.TransformFromDevice;
var mouse = transform.Transform(GetMousePosition());

public System.Windows.Point GetMousePosition()
{
    System.Drawing.Point point = System.Windows.Forms.Control.MousePosition;
    return new System.Windows.Point(point.X, point.Y);
}

#5


2  

This works without having to use forms or import any DLLs:

这无需使用表单或导入任何dll:

   using System.Windows;
   using System.Windows.Input;

    /// <summary>
    /// Gets the current mouse position on screen
    /// </summary>
    private Point GetMousePosition()
    {
        // Position of the mouse relative to the window
        var position = Mouse.GetPosition(Window);

        // Add the window position
        return new Point(position.X + Window.Left, position.Y + Window.Top);
    }

#6


0  

You may use combination of TimerDispatcher (WPF Timer analog) and Windows "Hooks" to catch cursor position from operational system.

您可以使用TimerDispatcher (WPF计时器模拟)和Windows“钩子”组合来捕获操作系统中的游标位置。

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetCursorPos(out POINT pPoint);

Point is a light struct. It contains only X, Y fields.

Point是一个轻结构体。它只包含X Y字段。

    public MainWindow()
    {
        InitializeComponent();

        DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
        dt.Tick += new EventHandler(timer_tick);
        dt.Interval = new TimeSpan(0,0,0,0, 50);
        dt.Start();
    }

    private void timer_tick(object sender, EventArgs e)
    {
        POINT pnt;
        GetCursorPos(out pnt);
        current_x_box.Text = (pnt.X).ToString();
        current_y_box.Text = (pnt.Y).ToString();
    }

    public struct POINT
    {
        public int X;
        public int Y;

        public POINT(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }

This solution is also resolving the problem with too often or too infrequent parameter reading so you can adjust it by yourself. But remember about WPF method overload with one arg which is representing ticks not milliseconds.

该解决方案还解决了参数读取频率过高或过低的问题,因此您可以自己调整它。但是请记住WPF方法重载,使用一个arg表示节拍,而不是毫秒。

TimeSpan(50); //ticks