[英]How can I get X, Y positions of mouse relative to form even when clicking on another control?
目前,我將鼠標懸停在表格上會在標簽上顯示x,y線。 雖然單擊該標簽,但沒有收到鼠標按下的標簽。 但是,當我將代碼放入標簽的mousedown中時,它會根據標簽的來源而不是整個表格給出編碼。
我的目標是能夠檢測表單中任何位置的x,y。 即使在標簽上,也要按下按鈕。
提前致謝。
似乎有點hack,但是...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
foreach (Control c in this.Controls)
{
c.MouseDown += ShowMouseDown;
}
this.MouseDown += (s, e) => { this.label1.Text = e.X + " " + e.Y; };
}
private void ShowMouseDown(object sender, MouseEventArgs e)
{
var x = e.X + ((Control)sender).Left;
var y = e.Y + ((Control)sender).Top;
this.label1.Text = x + " " + y;
}
}
protected override void OnMouseMove(MouseEventArgs mouseEv)
{
txtBoxX.Text = mouseEv.X.ToString();
txtBoxY.Text = mouseEv.Y.ToString();
}
您可以在窗體上為每個控件獲取像this.PointToClient(Cursor.Position)這樣的位置。
我意識到這是前一陣子,但我認為這可能會對某人有所幫助。 我認為解決此問題的方法是遞歸的:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
label1.MouseDown += MyMouseDown;
}
void MyMouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)//If it's left button that's the trigger
{
Control c = (Control)sender;
if (c.Parent == null) return;//Has no more children, wrong condition?
if(c.Parent != this)//We've reached top level
{
MyMouseDown(c.Parent, new MouseEventArgs(e.Button,
e.Clicks,
c.Parent.Location.X + e.X,
c.Parent.Location.Y + e.Y,
e.Delta));
return;
}
//Do what shall be done here...
}
}
}
您可以通過this.Location
進行調整。
或在窗體和每個控件上使用this.PointToClient(Cursor.Position)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.