C# 如何在对象之间继承事件
我需要继承事件和属性。例如,我需要在窗体周围移动图片。 我有这个代码来移动一张图片,但我需要创建具有相同行为的多张图片C# 如何在对象之间继承事件,c#,winforms,inheritance,picturebox,C#,Winforms,Inheritance,Picturebox,我需要继承事件和属性。例如,我需要在窗体周围移动图片。 我有这个代码来移动一张图片,但我需要创建具有相同行为的多张图片 private void pictureBox_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { x = e.X; y = e.Y; } } private void pictureBox_Mouse
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
x = e.X;
y = e.Y;
}
}
private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
pictureBox.Left += (e.X -x);
pictureBox.Top += (e.Y - y);
}
}
您真正想要做的是让多个PictureBoxe共享相同的事件处理程序:
private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// the "sender" of this event will be the picture box who fired this event
PictureBox thisBox = sender as PictureBox;
thisBox.Left += (e.X -x);
thisBox.Top += (e.Y - y);
}
}
您在表单上创建的每个PictureBox都会将它们连接到同一个已创建的事件。如果查看上面的代码,您会注意到它决定了哪个PictureBox调用它,并且只影响该图片框。您真正想要做的是让多个PictureBox共享相同的事件处理程序:
private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// the "sender" of this event will be the picture box who fired this event
PictureBox thisBox = sender as PictureBox;
thisBox.Left += (e.X -x);
thisBox.Top += (e.Y - y);
}
}
您在表单上创建的每个PictureBox都会将它们连接到同一个已创建的事件。如果查看上面的代码,您会注意到它确定了调用它的PictureBox,并且只影响该图片框。创建自定义控件:
public class MovablePictureBox : PictureBox
{
private int x;
private int y;
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left)
{
x = e.X;
y = e.Y;
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.Button == MouseButtons.Left)
{
Left += (e.X - x);
Top += (e.Y - y);
}
}
}
更新:
按照Microsoft的建议,您应该覆盖继承的事件功能,而不是附加委托。
创建此控件后,只需编译程序并将MovablePictureBoxes从工具箱拖动到窗体。它们都可以拖动(或移动,如果您愿意)。创建自定义控件:
public class MovablePictureBox : PictureBox
{
private int x;
private int y;
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left)
{
x = e.X;
y = e.Y;
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.Button == MouseButtons.Left)
{
Left += (e.X - x);
Top += (e.Y - y);
}
}
}
更新:
按照Microsoft的建议,您应该覆盖继承的事件功能,而不是附加委托。
创建此控件后,只需编译程序并将MovablePictureBoxes从工具箱拖动到窗体。它们都是可拖动的(或可移动的,如果您愿意)。谢谢,但是当我想要实现您在编程picturebox时提到的自定义控件时,我遇到了一个问题。如何以编程方式为主类中的每个picturebox使用此自定义控件thanks@marduck19,如果您想以编程方式创建它们,那么只需创建与标准图片框完全相同的图片框,但使用类名MovablePictureBox即可。例如,
var pictureBox=new MovablePictureBox()
感谢您的帮助,我非常理解。来自瓜达拉哈拉墨西哥的问候=)@marduck19,很高兴我能帮上忙:)谢谢,但是当我想要实现你在编程picturebox时提到的自定义控件时,我遇到了一个问题。如何以编程方式为主类中的每个picturebox使用此自定义控件thanks@marduck19,如果您想以编程方式创建它们,那么只需创建与标准图片框完全相同的图片框,但使用类名MovablePictureBox即可。例如,var pictureBox=new MovablePictureBox()
感谢您的帮助,我非常理解。来自瓜达拉哈拉墨西哥的问候=)@marduck19,很高兴我能帮忙:)