禁用所有鼠标消息

时间:2018-10-19 15:22:41

标签: c# .net winforms

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

是否有一种方法可以将鼠标悬停在该控件上(单击按钮除外)来禁用所有消息?

我什么都找不到。

1 个答案:

答案 0 :(得分:1)

根据您的描述,我认为足以过滤掉发送到控件的MouseMove消息。这可以通过使Form实现IMessageFilter类似于下面提供的示例来完成。从true返回IMessageFilter.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
    }
}
相关问题