我有一些自定义控件的实例,可以在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;
}
}
}
问题在于,当我提出一个事件时,它只由发送者处理,当我需要所有控件来处理它时。我怎么能这样做?
先谢谢你,伊万。
答案 0 :(得分:1)
选项1
我会在控件上使用静态事件
public static event GroupMoveEventHandler GroupMoveEvent;
那么你的事件处理程序也需要是静态的
protected static virtual void
OnGroupMoveEvent(object sender, GroupMoveEventArgs e)
{
注意 如评论中所述,请确保引用您的静态事件
GroupMoveEventHandler -= OnGroupMoveEvent;
如果您想了解更多信息,请参阅Static Events的示例
选项2
将您的事件处理程序放在包含控件的表单中,并在使所有实例控件将控件中的事件形式的单个事件处理程序分配给控件
之后格式
Control c = new control();
c.GroupMoveEventHandler += figureMouseMove(object sender, MouseEventArgs e);
public delegate void GroupMoveEventHandler(object sender,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));
}
}
}