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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4226740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:20:39  来源:igfitidea点击:

How do I get the current mouse screen coordinates in WPF?

wpfmouse-coordinates

提问by Prince OfThief

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,但我想在不使用元素的情况下获得协调。

回答by erikH

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))
}

回答by Fredrik Hedblad

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);
}

回答by Rachel

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.Formsand use:

如果没有,我相信您可以添加引用System.Windows.Forms并使用:

System.Windows.Forms.Control.MousePosition;

回答by Alexandru

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

如果您在不同分辨率、具有多个显示器的计算机等上尝试了很多这些答案,您可能会发现它们不能可靠地工作。这是因为您需要使用变换来获取相对于当前屏幕的鼠标位置,而不是包含所有显示器的整个查看区域。像这样的东西......(其中“这个”是一个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);
}

回答by hemligaarne

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);
    }

回答by Max Bender

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

您可以使用 TimerDispatcher(WPF Timer 模拟)和 Windows“Hooks”的组合来从操作系统中捕获光标位置。

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

点是光struct。它仅包含 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 ticksnot milliseconds.

该方案还解决了参数读取太频繁或太不频繁的问题,因此您可以自行调整。但请记住 WPF 方法重载,其中一个 arg 表示ticksnot milliseconds

TimeSpan(50); //ticks

回答by Jesse Grunert

If you're looking for a 1 liner, this does well.

如果您正在寻找 1 班轮,这很好。

new Point(Mouse.GetPosition(mWindow).X + mWindow.Left, Mouse.GetPosition(mWindow).Y + mWindow.Top)

回答by hossein sedighian

i add this for use with controls

我添加这个用于控件

   private void Control_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
 var mousepos = new List<double> { e.GetPosition(ControlName).X, e.GetPosition(ControlName).Y };

}

回答by Fire1nRain

Mouse.GetPosition(mWindow)gives you the mouse position relative to the parameter of your choice. mWindow.PointToScreen()convert the position to a point relative to the screen.

Mouse.GetPosition(mWindow)为您提供相对于您选择的参数的鼠标位置。 mWindow.PointToScreen()将位置转换为相对于屏幕的点。

So mWindow.PointToScreen(Mouse.GetPosition(mWindow))gives you the mouse position relative to the screen, assuming that mWindowis a window(actually, any class derived from System.Windows.Media.Visualwill have this function), if you are using this inside a WPF window class, thisshould work.

所以mWindow.PointToScreen(Mouse.GetPosition(mWindow))给你鼠标相对于屏幕的位置,假设它mWindow是一个窗口(实际上,任何派生自的类System.Windows.Media.Visual都会有这个功能),如果你在 WPF 窗口类中使用它,this应该可以工作。