在我的表单中,我有几个控件,每个控件都有一个MouseMove事件处理程序。当表单最大化/未最大化时,如何触发这些事件(Control.MouseMove)?以下代码演示了如何为每个控件分配事件处理程序。感谢您的帮助和建议。
control.MouseMove += delegate(object sender, MouseEventArgs e)
{
if (Dragging)
{
if (direction != Direction.Vertical)
container.Left = Math.Max(0, e.X + container.Left - DragStart.X);
if (direction != Direction.Horizontal)
container.Top = Math.Max(0, e.Y + container.Top - DragStart.Y);
}
};
答案 0 :(得分:1)
事件只能由每个定义的实现类触发。 但是,您可以将MouseMove,Maximize和Minimize事件定位到与原始MouseMove委托相同范围内创建的同一非匿名委托,以保留对本地变量的使用。
您需要自己在表单中创建最大化和最小化的事件,因为它们不是在winforms中提供的(请参阅Event when a window gets maximized/un-maximized)
public event Action<object> Maximized;
public event Action<object> Minimized;
protected override void WndProc(ref Message m) {
if (m.Msg == 0x0112) { // WM_SYSCOMMAND
// Check your window state here
if (m.WParam == new IntPtr(0xF030) && Maximized != null) Maximized(this);// Maximize event - SC_MAXIMIZE from Winuser.h
if (m.WParam == new IntPtr(0XF020) && Minimized != null) Minimized(this);// Minimize event - SC_MINIMIZE from Winuser.h
}
base.WndProc(ref m);
}
您之前的代码可以重新编写为:
var MMove = new Action<Point>(mousePosition =>
{
if (Dragging)
{
if (direction != Direction.Vertical)
container.Left = Math.Max(0, mousePosition.X + container.Left - DragStart.X);
if (direction != Direction.Horizontal)
container.Top = Math.Max(0, mousePosition.Y + container.Top - DragStart.Y);
}
});
this.MouseMove += (sender,e) => MMove(e.Location);
this.Maximized += (sender) => MMove(MousePosition);
this.Minimized += (sender) => MMove(MousePosition);