我有以下问题:
我有一个带有两个文本框的窗口。当我点击一个文本框然后点击其他任何地方(甚至在窗口外)时,鼠标点击位置应该被写入文本框。
我找到了 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/