c# - 在 TextBox 中写入绝对鼠标位置

标签 c# wpf textbox mouse-position

我有以下问题:

我有一个带有两个文本框的窗口。当我点击一个文本框然后点击其他任何地方(甚至在窗口外)时,鼠标点击位置应该被写入文本框。

我找到了 MouseKeyHook 库,其中演示了如何在 Windows 窗体中更新鼠标位置。但是我还没有设法将代码应用于我的问题。我什至不知道应该在哪里编写在演示中找到的代码。

到目前为止我想出的是:

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

namespace LineClicker
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void StarttextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            Mouse.Capture(StarttextBox);
            StarttextBox.Text = string.Format(" x {0} , y {1}", PointToScreen(Mouse.GetPosition(this)).X, PointToScreen(Mouse.GetPosition(this)).Y);
        }
    }
}

这是一个文本框的代码。当我点击它时,会显示 x 和 y 坐标。它们不是绝对的,我认为这是由于 GetPosition 方法中的参数 this 所致。我必须选择什么来代替 this

另一件事是位置并不总是更新。当我将鼠标移动到桌面的右下角,然后通过按 Tab 键进入文本框来激活文本框时,该位置没有得到更新。

这里的步骤是什么?

最佳答案

我能够使用 Cursor.Position 获得此结果:

A Point that represents the cursor's position in screen coordinates.

示例

using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void textBox_GotFocus(object sender, RoutedEventArgs e)
        {
            var postion = System.Windows.Forms.Cursor.Position;
            textBox.Text = string.Format($"{postion.X}, {postion.Y}");
        }
    }
}

the Microsoft reference source可以看出Cursor.Position 定义为:

public static Point Position {
    get {
        NativeMethods.POINT p = new NativeMethods.POINT();
        UnsafeNativeMethods.GetCursorPos(p);
        return new Point(p.x, p.y);
    }
    set {
        IntSecurity.AdjustCursorPosition.Demand();
        UnsafeNativeMethods.SetCursorPos(value.X, value.Y);
    }
}

所以就像yan yankelevich's answer ,还是使用了SetCursorPos,但是这样调用起来更方便。

除此之外,它可能仅取决于您是否乐意包含对 System.Windows.Forms 的引用。

关于c# - 在 TextBox 中写入绝对鼠标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40399531/

相关文章:

c# - 在 WPF 中处理文本框上的 Enter 事件时,如何接受 Ctrl+Enter 作为返回?

用于检查用户是否在文本字段中输入空格的 Javascript

c# - 如何从 NuGet 安装 EntityFramework 5.0(和其他旧版本)?

c# - 如果没有数据(为空),应该保存什么(在 SQL Server 数据库中)?

c# - .mdf 文件和跨数据库查询?

javascript - 如何将从 MySQL 检索到的数组列表值设置到 JavaScript 中的文本框中?

C# 套接字接收方法不接收数据

WPF 覆盖 ContextMenu 样式 - DropShadowEffect 不起作用

c# - 现有数据库中代码优先的外键问题

c# - 清除 CheckBoxList 的值?