当笔位于按钮上时(WndProc方法),笔鼠标消息被抑制。如何解决这个问题?

时间:2019-06-12 08:37:35

标签: c# winforms mouse wndproc pen

我想随时随地跟踪笔的位置。我希望即使在按钮上也可以调用WndProc。但是,如果表单中有一个按钮,则不会发生wndProc。我该怎么办?

一些详细信息:

某些笔鼠标消息出现在wndProc的消息中。 (笔鼠标消息的Msg为0x0711)

如果我在表单内移动笔,则wndProc会继续提供该值。 但是,如果表单中存在按钮,则按钮上不会出现wndProc。

public const int PEN = 0x0711;
protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);

    if (PEN == m.Msg)
    {
       // TODO: function
    }
}

1 个答案:

答案 0 :(得分:0)

这没有经过测试,因为我没有钢笔,但从原理上讲,该概念应该有效。

使用IMessageFilter Interface实现来检测发送到表单或其子控件之一的PEN消息并执行所需的功能。

class PenFilter : IMessageFilter
{
    private const int PEN = 0x0711;
    private readonly Form parent;
    public PenFilter(Form parent)
    {
        this.parent = parent;
    }
    bool IMessageFilter.PreFilterMessage(ref Message m)
    {
        Control targetControl = Control.FromChildHandle(m.HWnd);
        if (targetControl != null && (targetControl == parent || parent == targetControl.FindForm()))
        {
            // execute your function
        }
        return false;
    }
}

基于激活/停用表单安装/删除过滤器。

public partial class Form1 : Form
{
    private PenFilter penFilter;
    public Form1()
    {
        InitializeComponent();
        penFilter = new PenFilter(this);
    }

    protected override void OnActivated(EventArgs e)
    {
        Application.AddMessageFilter(penFilter);
        base.OnActivated(e);
    }
    protected override void OnDeactivate(EventArgs e)
    {
        Application.RemoveMessageFilter(penFilter);
        base.OnDeactivate(e);
    }
}