【问题标题】:How to trigger Control.MouseMove event when maximized/un-maximized form in winforms C#如何在winforms C#中最大化/未最大化表单时触发Control.MouseMove事件
【发布时间】:2015-02-13 07:52:31
【问题描述】:

在我的表单中,我有几个控件,每个控件都有一个 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);
     }
};

【问题讨论】:

    标签: c# winforms delegates event-handling


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      相关资源
      最近更新 更多