gpt4 book ai didi

c# - 如何在桌面上正确绘制矩形错误

转载 作者:行者123 更新时间:2023-11-30 18:40:02 27 4
gpt4 key购买 nike

我想捕获一个桌面区域,在桌面上绘制一个矩形。

为了实现这一点,我开发了一个名为 MouseHooker 的类,它安装了一个全局鼠标钩子(Hook),处理鼠标消息并通过委托(delegate)回调将其公开。

钩子(Hook)代码没问题,外部“回调”我也这么认为,但有一个奇怪的错误。

它钩住鼠标,但只有在鼠标左键向上移动后才会绘制矩形。

我不知道为什么。你能帮助我吗 ?谢谢

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);
}

最佳答案

如果我没理解错的话,你说的是绘制矩形时,绘制的位置偏离了你点击的位置。

如果只是少量,则可能是舍入误差。 MSLHOOKSTRUCT 将 pt 定义为一个点,它是两个 float 的结构,而不是两个整数。( More info )

任何其他错误都与指针的测量位置(屏幕边缘)和绘图事件的测量位置(我们看不到,因为您没有发布图形对象已设置)

希望这对您有所帮助!

关于c# - 如何在桌面上正确绘制矩形错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8926256/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com