如果你的项目在WindowsFormApplicaiton 那么
如果您的控件是button,就像屏幕截图中一样
然后你也可以访问它的位置到它的主屏幕并形成屏幕
下面是代码
private void button1_Click(object sender, EventArgs e)
{
//This code gives you the location of button1 wrt your primary working screen
Point location = this.PointToScreen(button1.Location);
int x1 = location.X;
int y1 = location.Y;
MessageBox.Show($"X: {x1}, Y: {y1}");
//This code gives you the location of button1 wrt your forms upper-left corner
Point relativeLoc = new Point(location.X - this.Location.X, location.Y - this.Location.Y);
int x2 = relativeLoc.X;
int y2 = relativeLoc.Y;
MessageBox.Show($"X: {x2}, Y: {y2}");
//This code gives you the location of button1 wrt your forms client area
Point relativeLoc1 = new Point(button1.Location.X, button1.Location.Y);
int x3 = relativeLoc1.X;
int y3 = relativeLoc1.Y;
MessageBox.Show($"X: {x3}, Y: {y3}");
}
在上面的代码中我使用了this,您可以根据需要使用任何forms 对象
编辑:
如果您不知道您的控件将被点击的位置,那么您必须为表单中的所有控件注册一个事件,例如
在下面的代码中,我使用了MouseHover 事件,但您可以根据需要使用任何事件
首先为Form1_Load 中的所有控件注册MouseHover 事件
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
c.MouseHover += myMouseHoverEvent;
}
那么你的自定义MouseHover事件就是
private void myMouseHoverEvent(object sender, EventArgs e)
{
Control control = sender as Control;
int x = control.Location.X;
int y = control.Location.Y;
MessageBox.Show($"X: {x}, Y: {y}");
}
试一次可能对你有帮助