这没有经过测试,因为我没有笔,但原则上这个概念应该有效。
使用IMessageFilter 接口实现来检测发送到窗体或其子控件之一的 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);
}
}