David P David P - 1 month ago 12
C# Question

Write absolute mouse position in TextBox

I have the following issue:

I have window with two textboxes. When I click in a textbox and then click anywhere else (even outside the window), the mouse click position should be written into the textbox.

I found the

MouseKeyHook
library, in which a demo shows how the mouse position is updated in a windows form. But I did not manage to apply the code to my problem yet. I don't even know where I should write the code found in the demo.

What I came up with so far is the following:

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


This is the code for one textBox. When I click in it, x and y coordinates are displayed. They are not absolute, I think this is due to the parameter
this
in the
GetPosition
method. What do I have to choose instead of
this
?

Another thing is that the position is not updated always. When I move the mouse to the lower right corner of my desktop and then activate the textbox by tabbing into it, the position doesn't get updated.

What are the steps to do here?

Answer

I was able to achieve this result using Cursor.Position:

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

Example

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

You can see from the the Microsoft reference source that Cursor.Position is defined as:

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

So just like in yan yankelevich's answer, it still uses SetCursorPos, but this way it is easier to call.

Apart from that it probably just depends on whether or not you are happy to include the reference to System.Windows.Forms.

Comments