Это не было проверено, поскольку у меня нет пера, но в принципе концепция должна работать.
Используйте реализацию Интерфейс 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);
}
}