禁止滑鼠作用於特定控件 (如 ListBox) 或整個視窗,僅保留鍵盤關閉功能。
IMessageFilter
public class MouseMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
// 0x100 = WM_KEYDOWN, 0x11 = VK_CONTROL (示例)
// 實際滑鼠訊息: 0x200=WM_MOUSEMOVE, 0x201=WM_LBUTTONDOWN, 0x202=WM_LBUTTONUP, 0x203=WM_LBUTTONDBLCLK
// 0x204=WM_RBUTTONDOWN, 0x205=WM_RBUTTONUP, 0x206=WM_RBUTTONDBLCLK
if (m.Msg >= 0x200 && m.Msg <= 0x206) // 攔截所有滑鼠訊息
{
return true; // true = 過濾掉(不再分派)
}
return false;
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
var filter = new MouseMessageFilter();
Application.AddMessageFilter(filter); // 註冊
Application.Run(new Form1());
Application.RemoveMessageFilter(filter); // 移除
}
PreFilterMessage 中判斷 m.HWnd 針對特定控件過濾。Control.FromHandle 取得控件實例進一步判斷邏輯。WM_LBUTTONDOWN) 允許滑鼠移動但禁止點擊。應用層級訊息過濾器提供全域攔截能力,比控件層級事件處理更徹底。