我想在表格上获取光标位置。
下面的代码有效,但当光标位于某些pictureBox上时无效。
所以我需要一些帮助。
谢谢!
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
Point p = Cursor.Position;
label1.Text = "x= " + p.X.ToString();
label2.Text = "y= " + p.Y.ToString();
}
答案 0 :(得分:1)
您必须订阅该图片框的MouseMove
事件并在其中调用您的方法。
// in Form1.cs
private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
{
OnMouseMove(e);
}
或者您可以覆盖表单的CreateControlsInstance
方法以返回自定义控件集合,该集合将订阅每个子控件的MouseMove
事件
// in Form1.cs
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
Point p = Cursor.Position;
label1.Text = "x= " + p.X.ToString();
label2.Text = "y= " + p.Y.ToString();
}
class Form1ControlCollection : ControlCollection
{
Form1 owner;
internal Form1ControlCollection(Form1 owner) : base(owner)
{
this.owner = owner;
}
public override void Add(Control value)
{
base.Add(value);
value.MouseMove += Value_MouseMove;
}
private void Value_MouseMove(object sender, MouseEventArgs e)
{
owner.OnMouseMove(e);
}
}
protected override Control.ControlCollection CreateControlsInstance()
{
return new Form1ControlCollection(this);
}
将此代码段添加到您的表单中
答案 1 :(得分:0)
我想这是因为您仅重写了OnMouseMove-Form的方法。要捕获图片框(或任何控件)中的鼠标移动事件,请使用控件中的MouseMove-事件。
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
Point p = Cursor.Position;
label1.Text = "x= " + p.X.ToString();
label2.Text = "y= " + p.Y.ToString();
}
答案 2 :(得分:0)
谢谢你们!
这对我有用。
在受保护的重写中void OnMouseMove(MouseEventArgs e) 您可以同时使用注释或取消注释代码
private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
{
OnMouseMove(e);
}
private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
{
OnMouseMove(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
//base.OnMouseMove(e);
//Point p = Cursor.Position;
//label1.Text = "x= " + p.X.ToString();
//label2.Text = "y= " + p.Y.ToString();
label1.Text = "x= " + e.X.ToString();
label2.Text = "y= " + e.Y.ToString();
}