0

我有几个自定义控件的实例,它们在 MouseMove 上引发自定义事件。这是代码: EventArgs 类:

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;
        }
    }
}

问题是当我引发一个事件时,它只由发送者处理,而我需要所有控件来处理它。我怎样才能做到这一点?

在此先感谢,伊万。

4

1 回答 1

2

选项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);

公共委托无效 GroupMoveEventHandler(对象发送者,GroupMoveEventArgs e);公共事件 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));
         }
      }
    }  
于 2012-05-11T11:48:39.497 回答