我在下面使用此代码,但它并不像我想要的那样工作,我不知道如何实际制作它。
我想要它做的是获取鼠标坐标onClick
,但这会在用户确认消息框后发生。
MessageBox>用户单击确定>用户点击屏幕上的任意位置>获取坐标
我应该在"确定按钮"?我在定时器代码上做什么等待鼠标响应?
这就是我现在的(当我点击OK按钮时显示鼠标位置):
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);
}
}
答案 0 :(得分:1)
你快到了。问题是,EventArgs
会在点击时为您提供相对于按钮的位置
如果您想要光标位置而不是点击,您可以使用Cursor
类来获取其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
后获取坐标,您可以使用计时器。为此,您必须在类级别声明一个,设置其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();
}
}
答案 1 :(得分:1)
相对于屏幕的光标位置
System.Windows.Forms.Cursor.Position
相对于控件的光标位置
var relativePoint = myControl.PointToClient(Cursor.Position);
.NET Framework不支持全局挂钩。请参阅Reference
如果您想处理全局鼠标点击事件,请查看本文。