单击鼠标获取鼠标坐标

Getting mouse coordinates on mouse click

我正在使用下面的这段代码,但它并没有像我想要的那样工作,而且我不知道如何实际制作它。

我想要它做的是获取鼠标坐标 onClick,但这是在用户确认消息框后发生的。

MessageBox > 用户单击确定 > 用户单击屏幕上的任意位置 > 获取坐标

我应该在 "OK button" 开始计时吗?我在定时器代码上做了什么来等待鼠标响应?

这就是我现在所拥有的(当我单击“确定”按钮时显示鼠标位置):

private void button12_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Pick a position after clicking OK", "OK", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) == DialogResult.OK)
    {
        // user clicked ok
        MouseEventArgs me = (MouseEventArgs)e;
        Point coordinates = me.Location;
        MessageBox.Show("Coordinates are: " + coordinates);
    }
}

你快到了。问题是 EventArgs 会在点击时为您提供相对于按钮 的位置

如果你想要光标位置而不是点击,你可以使用Cursorclass来获取它的Position属性:

private void button12_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Pick a position after clicking OK", "OK", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) == DialogResult.OK)
    {
        // user clicked ok
        Point coordinates = Cursor.Position;
        MessageBox.Show("Coordinates are: " + coordinates);
    }
}

要在用户关闭 MessageBox 后获取坐标,您可以使用计时器。为此,您必须在 class 级别声明一个,设置其 Tick 事件并将您的光标登录移动到其中。

button12_Click 方法现在将启动定时器,一旦定时器到期(在本例中为一秒后),它将显示光标位置。

private Timer timer; //Declare the timer at class level
public Form1()
{
    InitializeComponent();
    // We set it to expire after one second, and link it to the method below
    timer = new Timer {Interval = 1000}; //Interval is the amount of time in millis before it fires
    timer.Tick += OnTick;
}

private void OnTick(object sender, EventArgs eventArgs)
{
    timer.Stop(); //Don't forget to stop the timer, or it'll continue to tick
    Point coordinates = Cursor.Position;
    MessageBox.Show("Coordinates are: " + coordinates);
}


private void button1_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Pick a position after clicking OK", "OK", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) == DialogResult.OK)
    {
        timer.Start();
    }
}

光标相对于屏幕的位置

System.Windows.Forms.Cursor.Position

光标相对于控件的位置

var relativePoint = myControl.PointToClient(Cursor.Position);

.NET Framework 不支持全局挂钩。 请参阅 Reference

如果你想处理全局鼠标点击事件,请看这篇文章。

Processing Global Mouse and Keyboard Hooks in C#