【发布时间】:2021-12-12 08:16:41
【问题描述】:
您好,我的代码有问题。我在表单上添加了 44 个标签,并尝试以这种方式为每个标签制作 2 个事件处理程序:
/// <summary>
/// Adds event handler methods to all Label controls on current form using foreach loop,
/// these handlers handle MouseDown and MouseMove events
/// </summary>
public void AddEventToLabels()
{
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(Label))
{
c.MouseDown += new MouseEventHandler(this.Label_MouseDown);
c.MouseMove += new MouseEventHandler(this.Label_MouseMove);
}
}
}
/// <summary>
/// Executes when button of mouse is pressed by user and cursor is over the control
/// </summary>
/// <param name="sender">The source of the event</param>
/// <param name="e">Provides data for the MouseUp, MouseDown, and MouseMove events</param>
public void Label_MouseDown(object sender, MouseEventArgs e)
{
md.StoreMouseLocation(e); //Just a method to store location of cursor
}
/// <summary>
/// Executes when user moves mouse and cursos is over the control
/// </summary>
/// <param name="sender">The source of the event</param>
/// <param name="e">Provides data for the MouseUp, MouseDown, and MouseMove events</param>
public void Label_MouseMove(object sender, MouseEventArgs e)
{
var label = sender as Label; //Casts sender object to control on current form
md.MoveControl(e, label); //Moves label with cursor
}
但是这些处理程序不起作用,我不明白为什么。那么,我怎样才能让它正常工作?
【问题讨论】:
-
foreach (var c in this.Controls.OfType<Label>()) { ... }。确保标签确实由Form托管,而不是其他容器。 -
是的,你是对的
标签: c# winforms event-handling controls mouseevent