我在c#(Visual Studio)
上遇到了Eventhandler的问题我的代码:
private void button1_Click(object sender, EventArgs e)
{
this.lastCreatedPanel++;
SizeablePanel sp = new SizeablePanel();
sp.BackColor = Color.Gray;
sp.Name = "DynamicPanel_" + lastCreatedPanel;
sp.BorderStyle = BorderStyle.FixedSingle;
Label label = new Label();
label.Text = "X";
label.Location = new Point(1, 1);
label.MouseDown += new MouseEventHandler(this.Panel_MouseDown);
label.MouseMove += new MouseEventHandler(this.Panel_MouseMove);
sp.Controls.Add(label);
}
private void Panel_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
loc = e.Location;
}
}
private void Panel_MouseMove(object sender, MouseEventArgs e)
{
Control ctrl = sender as Control;
if (e.Button == MouseButtons.Left)
{
ctrl.Left += e.X - loc.X;
ctrl.Top += e.Y - loc.Y;
table.Invalidate();
}
}
我需要为动态创建的面板运行Panel_MouseDown和Panel_MouseMove函数 - 而不是标签。标签只是控制捕获。
我该怎么做?
非常感谢。
答案 0 :(得分:0)
创建面板后,只需附上EventHandlers
,如下所示:
var panel = new Panel();
panel.MouseDown += Panel_MouseDown;
panel.MouseMove += Panel_MouseMove;