首页 > 解决方案 > 禁用控件上的所有鼠标消息

问题描述

我有一个绘制数据点的图形控件。数据点被绘制为每像素 1 个点。如果数据点的数量大于一定数量,或者窗口大小增加,则当您将鼠标移到控件上时,绘图的性能会受到影响。如果您快速移动,则绘图实际上会在运动过程中停止。

当鼠标悬停在该控件上时,除了单击按钮之外,有没有办法禁用所有消息?

我找不到任何东西。

标签: c#.netwinforms

解决方案


根据您的描述,我认为过滤掉发送到控件的 MouseMove 消息就足够了。这可以通过让 Form 实现IMessageFilter来完成,类似于下面的示例。Returning truefromIMessageFilter.PreFilterMessage阻止消息被发送到控件(示例中的面板)。已注册的过滤器在应用程序范围内是活动的,因此在表单激活/停用时添加/删除。

public partial class Form1 : Form, IMessageFilter
{
    private Panel pnl;

    public Form1()
    {
        InitializeComponent();
        pnl = new Panel { Size = new Size(200, 200), Location = new Point(20, 20), BackColor = Color.Aqua };
        Controls.Add(pnl);
        pnl.Click += panel_Click;
        pnl.MouseMove += panel_MouseMove;
        pnl.MouseHover += panel_MouseHover;

    }

    private void panel_MouseHover(sender As Object, e As EventArgs)
    {
        // this should not occur
        throw new NotImplementedException();
    }

    private void panel_MouseMove(object sender, MouseEventArgs e)
    {
        // this should not occur
        throw new NotImplementedException();
    }

    private void panel_Click(object sender, EventArgs e)
    {
        MessageBox.Show("panel clicked");
    }

    protected override void OnActivated(EventArgs e)
    {
        base.OnActivated(e);
        // install message filter when form activates
        Application.AddMessageFilter(this);
    }

    protected override void OnDeactivate(EventArgs e)
    {
        base.OnDeactivate(e);
        // remove message filter when form deactivates
        Application.RemoveMessageFilter(this);
    }

    bool IMessageFilter.PreFilterMessage(ref Message m)
    {
        bool handled = false;
        if (m.HWnd == pnl.Handle && (WM) m.Msg == WM.MOUSEMOVE)
        {
            handled = true;
        }
        return handled;
    }

    public  enum WM : int
    {
        #region Mouse Messages
        MOUSEFIRST = 0x200,
        MOUSEMOVE = 0x200,
        LBUTTONDOWN = 0x201,
        LBUTTONUP = 0x202,
        LBUTTONDBLCLK = 0x203,
        RBUTTONDOWN = 0x204,
        RBUTTONUP = 0x205,
        RBUTTONDBLCLK = 0x206,
        MBUTTONDOWN = 0x207,
        MBUTTONUP = 0x208,
        MBUTTONDBLCLK = 0x209,
        MOUSELAST = 0x209
        #endregion
    }
}

推荐阅读