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

发布于 2024-10-03 01:08:22 字数 102 浏览 2 评论 0原文

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

拍不死你 2024-10-10 01:08:22

或者在纯 WPF 中使用 PointToScreen

示例辅助方法:

// Gets the absolute mouse position, relative to screen
Point GetMousePos() => _window.PointToScreen(Mouse.GetPosition(_window));

Or in pure WPF use PointToScreen.

Sample helper method:

// Gets the absolute mouse position, relative to screen
Point GetMousePos() => _window.PointToScreen(Mouse.GetPosition(_window));
森罗 2024-10-10 01:08:22

跟进雷切尔的回答。
以下是在 WPF 中获取鼠标屏幕坐标的两种方法。

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

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

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()
{
    var w32Mouse = new Win32Point();
    GetCursorPos(ref w32Mouse);

    return new Point(w32Mouse.X, w32Mouse.Y);
}

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

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

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

2.Using 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()
{
    var w32Mouse = new Win32Point();
    GetCursorPos(ref w32Mouse);

    return new Point(w32Mouse.X, w32Mouse.Y);
}
微暖i 2024-10-10 01:08:22

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

如果它在应用程序中,只需使用:

Mouse.GetPosition(Application.Current.MainWindow);

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

System.Windows.Forms.Control.MousePosition;

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.Forms.Control.MousePosition;
带刺的爱情 2024-10-10 01:08:22

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

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

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

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

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

public System.Windows.Point GetMousePosition()
{
    var point = Forms.Control.MousePosition;
    return new Point(point.X, point.Y);
}
梦毁影碎の 2024-10-10 01:08:22

这无需使用表单或导入任何 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);
    }

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

   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);
    }
淤浪 2024-10-10 01:08:22

您可以结合使用 TimerDispatcher(WPF 计时器模拟)和 Windows“Hooks”来从操作系统捕获光标位置。

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

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

该方案还解决了参数读取太频繁或太少的问题,您可以自行调整。但请记住,带有一个参数的 WPF 方法重载代表的是“刻度”而不是“毫秒”。

TimeSpan(50); //ticks

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

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

    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.

TimeSpan(50); //ticks
清风夜微凉 2024-10-10 01:08:22

如果您正在寻找 1 衬垫,这款就很适合。

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

+ mWindow.Left+ mWindow.Top 确保即使用户拖动窗口时位置也位于正确的位置。

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

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

The + mWindow.Left and + mWindow.Top makes sure the position is in the right place even when the user drags the window around.

分開簡單 2024-10-10 01:08:22

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

所以 mWindow.PointToScreen(Mouse.GetPosition(mWindow)) 为您提供鼠标相对于屏幕的位置,假设 mWindow 是一个窗口(实际上,任何从 派生的类code>System.Windows.Media.Visual 将具有此函数),如果您在 WPF 窗口类中使用此函数,则 this 应该可以工作。

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.

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

夜访吸血鬼 2024-10-10 01:08:22

我想使用这个代码

Point PointA;
private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e) {
    PointA = e.MouseDevice.GetPosition(sender as UIElement);
}

private void Button_Click(object sender, RoutedEventArgs e) {
    // use PointA Here
}

I wanna use this code

Point PointA;
private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e) {
    PointA = e.MouseDevice.GetPosition(sender as UIElement);
}

private void Button_Click(object sender, RoutedEventArgs e) {
    // use PointA Here
}
木槿暧夏七纪年 2024-10-10 01:08:22

在纯 WPF 中获取当前窗口实例('this')的鼠标绝对坐标(在双 4K 屏幕上测试)

System.Windows.Point  MousePos  =  this.PointToScreen( System.Windows.Input.Mouse.GetPosition(this));

To get the mouse absolute coordinates (tested on dual 4K screens) in pure WPF for the current window instance ('this')

System.Windows.Point  MousePos  =  this.PointToScreen( System.Windows.Input.Mouse.GetPosition(this));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文