不抱怨了,直接說答案,就是用 Global Mouse Hook, 然後把 Mouse Message 濾掉。是有不少例子在說明 mouse hook, 例如我看的最懂的是Processing Global Mouse and Keyboard Hooks in C#,卻沒有人講明白怎樣濾掉 mouse message.
事實上在該文中有答案,只是它沒明說而已。我直接寫一個範例片段來說明,當然說明直接放程式片段中:
// 註冊 global mouse hook
void TFormPaint::RegMouseHook()
{
MouseHookDelegate = gcnew HookProcDelegate(this, &TFormPaint::MouseHookProc);
MouseHookHandle = ::SetWindowsHookEx(WH_MOUSE_LL, MouseHookDelegate,
Marshal::GetHINSTANCE(System::Reflection::Assembly::GetExecutingAssembly()->GetModules()[0]),0);
}
// 我們處理的 mouse hook 的函式
int TFormPaint::MouseHookProc(int nCode, int wParam, IntPtr lParam)
{
WCHAR Buffer[30];
// 把 Mouse Hook 的訊息從 lParam 指標中取出來
MOUSEHOOKSTRUCT* mouseHookStruct=(MOUSEHOOKSTRUCT*)lParam.ToPointer();
// 只濾掉發生在本視窗的滑鼠事件,
// 所以要比對滑鼠所發生時的視窗
HWND CurHwnd = WindowFromPoint(mouseHookStruct->pt);
GetWindowText(CurHwnd, Buffer, 30);
String^ WindowTitle = gcnew String(Buffer);
// ☆重點來了,
// 當發現滑鼠事件是作用在我們的視窗上,就以
// return -1 來濾掉
if (WindowTitle->IndexOf(this->Text) != -1)
{
return -1;
}
// 下面這行非常重要,否則整個系統的滑鼠會因此壞掉
return CallNextHookEx(MouseHookHandle, nCode, wParam, lParam);
}
0 意見:
張貼留言