3
我想要在桌面上捕獲繪製矩形的桌面區域。如何正確在桌面上繪製矩形的問題
爲了達到這個目標,我已經開發了一個名爲MouseHooker類,它安裝全局鼠標鉤子,鼠標的過程信息和通過回調以委託暴露出來。
鉤子代碼它的確定,外面的「回調」我想太多,但有一個奇怪的錯誤。
它鉤住鼠標,但它的矩形只繪製後,如果鼠標左鍵時,鼠標移動。
我不知道爲什麼。你可以幫我嗎 ? 感謝
MouseHooker內部回調
private static IntPtr MyCallbackFunction(int code, UIntPtr wParam, IntPtr lParam)
{
// messsage not processed
if (code < 0)
SafeNativeMethods.CallNextHookEx(IntPtr.Zero,code,wParam,lParam);
// check outside callback subscribed to delegate (NOT IMPORTANT)
if (state != HookState.CallBackError)
{
MSLLHOOKSTRUCT hk = (MSLLHOOKSTRUCT)Marshal.PtrToStructure((IntPtr)lParam, typeof(MSLLHOOKSTRUCT));
MouseHookArgs m; // this struct only contains mouse coordinates and button
m.x = hk.pt.x; // clicked information
m.y = hk.pt.y;
// process mouse messages
switch ((MouseMessages)wParam)
{
case MouseMessages.WM_MOUSEMOVE:
m.button = MouseButtons.M_MOVE;
mc(m); // call outside "callback" mc its a delegate
break;
case MouseMessages.WM_LBUTTONUP:
m.button = MouseButtons.LB_UP;
mc(m);
break;
case MouseMessages.WM_LBUTTONDOWN:
m.button = MouseButtons.LB_DOWN;
mc(m);
break;
// more mouse message processing
}
// CallNextHookEx
return SafeNativeMethods.CallNextHookEx(IntPtr.Zero,code,wParam,lParam);
}
「回調」 的形式(這裏的錯誤,爲什麼?)
void callbackrect(MouseHookArgs args)
{
switch (args.button)
{
case ppk.Hooks.MouseButtons.LB_UP:
clean = true;
ok = true;
dest.X = args.x; // this struct its a Point
dest.Y = args.y;
// put destination mouse coordinate in form label
capt.Text = string.Format("X: {0} , Y: {1}", dest.X, dest.Y);
break;
case ppk.Hooks.MouseButtons.LB_DOWN:
if (clean)
{
clean = false;
ok = false;
}
origin.X = args.x; // get origin mouse coordinate (to draw rectangle)
origin.Y = args.y;
// put origin mouse coordinate in form label
rat.Text = string.Format("X: {0} , Y: {1}", origin.X, origin.Y);
break;
}
// Invalidate & Update Desktop RECT Unmanaged because it's a efficient
SafeNativeMethods.InvalidateRect(IntPtr.Zero, IntPtr.Zero, true);
SafeNativeMethods.UpdateWindow(IntPtr.Zero);
if (ok && clean) // Graphics g it's static and created in another location.
// Managed because creating a Pen, get DC, etc it's a pain
// and need more unmanaged code. So, why not use graphics ?
g.DrawRectangle(Pens.Red, origin.X, origin.Y, dest.X - origin.X, dest.Y - origin.Y);
}
「MouseHooker」... nice;) – musefan
callbackrect在哪裏使用,以及如何? – Tigran
@Tigran主窗體包含一個MouseHooker委託,此公共委託void MouseCallBack(MouseHookArgs mas);這個委託它被綁定到回調函數,所以當它被安裝的時候,「原始的」鼠標消息被MyCallBackFunction處理,並且通過mc委託對它進行回調。 – ppk