“全球”WinForms 事件

本文关键字:事件 WinForms 全球 | 更新日期: 2023-09-27 18:33:48

我有几个自定义控件的实例,这些实例在 MouseMove 上引发自定义事件。代码如下:事件参数类:

public class GroupMoveEventArgs
{
    public enum Action { CalcOffset, Move };
    Action action;
    int mouse_x;
    int mouse_y;
    // setters missed here
    public GroupMoveEventArgs(GroupMoveEventArgs.Action action,
        int mouse_x, int mouse_y)
    {
        this.action = action;
        this.mouse_x = mouse_x;
        this.mouse_y = mouse_y;
    }
}

控件类:

public delegate void GroupMoveEventHandler(object sender, GroupMoveEventArgs e);
public event GroupMoveEventHandler GroupMoveEvent;
protected virtual void figureMouseMove(object sender, MouseEventArgs e)
{
    if (mouseDown)
    {
        if (inGroup)
        {   // raising the event
            if (this.GroupMoveEvent != null)
                GroupMoveEvent(this, new GroupMoveEventArgs(
                               GroupMoveEventArgs.Action.Move,
                               Parent.PointToClient(Control.MousePosition).X,
                               Parent.PointToClient(Control.MousePosition).Y));
        }
    }
}
protected virtual void OnGroupMoveEvent(object sender, GroupMoveEventArgs e)
{
    Console.WriteLine("Got mouse move event " + this.num_of_points);
    if (inGroup)
    {
        if (e.EventAction == GroupMoveEventArgs.Action.Move)
        {
            Location = new Point(e.MouseX - offset.X, e.MouseY - offset.Y);
        }
        else
        if (e.EventAction == GroupMoveEventArgs.Action.CalcOffset)
        {
            Control c = sender as Control;
            Point pnt = Parent.PointToClient(Control.MousePosition);
            Point tmp = c.Location;
            offset.X = pnt.X - tmp.X;
            offset.Y = pnt.Y - tmp.Y;
        }
    }
}

问题是,当我引发一个事件时,它仅由发送者处理,而我需要所有控件来处理它。我该怎么做?

提前谢谢,伊万。

“全球”WinForms 事件

选项 1

我会在控件上使用静态事件

 public static event GroupMoveEventHandler GroupMoveEvent;

那么你的事件处理程序也需要是静态

 protected static virtual void 
                  OnGroupMoveEvent(object sender, GroupMoveEventArgs e)
 {

注意如注释中所述,请确保像这样引用静态事件

 GroupMoveEventHandler -= OnGroupMoveEvent;

这是静态事件的示例,如果您想了解更多信息

选项 2

将事件处理程序

放在包含控件的窗体中,并在使所有实例控件之后,将窗体中的单个事件处理程序从控件分配给事件

在形式中

 Control c = new control();
 c.GroupMoveEventHandler += figureMouseMove(object sender, MouseEventArgs e);

public delegate void GroupMoveEventHandler(object sender, GroupMoveEventArgs e); public event GroupMoveEventHandler GroupMoveEvent;

 protected virtual void figureMouseMove(object sender, MouseEventArgs e)
 {
     if (mouseDown)
     {
         if (inGroup)
         {   // raising the event
              if (this.GroupMoveEvent != null)
               GroupMoveEvent(this, new GroupMoveEventArgs(
                               GroupMoveEventArgs.Action.Move,
                               Parent.PointToClient(Control.MousePosition).X,
                               Parent.PointToClient(Control.MousePosition).Y));
         }
      }
    }