gpt4 book ai didi

c# - DrawIcon 在绘制图像时不使用光标 mask (I 形光标示例)

转载 作者:行者123 更新时间:2023-12-01 22:50:07 33 4
gpt4 key购买 nike

如果我在截图时使用DrawIcon,它可以正确地用 mask 绘制工字光标,但如果我想在任何图像上使用DrawIcon,则 mask 不起作用。

这个 DrawIcon 示例工作正常:

    public static Image CaptureRectangleNative(IntPtr handle, Rectangle rect, bool captureCursor = false)
{
if (rect.Width == 0 || rect.Height == 0)
{
return null;
}

IntPtr hdcSrc = NativeMethods.GetWindowDC(handle);
IntPtr hdcDest = NativeMethods.CreateCompatibleDC(hdcSrc);
IntPtr hBitmap = NativeMethods.CreateCompatibleBitmap(hdcSrc, rect.Width, rect.Height);
IntPtr hOld = NativeMethods.SelectObject(hdcDest, hBitmap);
NativeMethods.BitBlt(hdcDest, 0, 0, rect.Width, rect.Height, hdcSrc, rect.X, rect.Y, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt);

if (captureCursor)
{
Point cursorOffset = CaptureHelpers.ScreenToClient(rect.Location);

try
{
using (CursorData cursorData = new CursorData())
{
cursorData.DrawCursorToHandle(hdcDest, cursorOffset);
}
}
catch (Exception e)
{
DebugHelper.WriteException(e, "Cursor capture failed.");
}
}

NativeMethods.SelectObject(hdcDest, hOld);
NativeMethods.DeleteDC(hdcDest);
NativeMethods.ReleaseDC(handle, hdcSrc);
Image img = Image.FromHbitmap(hBitmap);
NativeMethods.DeleteObject(hBitmap);

return img;
}

// This function inside CursorData class
public void DrawCursorToHandle(IntPtr hdcDest, Point cursorOffset)
{
if (IconHandle != IntPtr.Zero)
{
Point drawPosition = new Point(Position.X - cursorOffset.X, Position.Y - cursorOffset.Y);
NativeMethods.DrawIcon(hdcDest, drawPosition.X, drawPosition.Y, IconHandle);
}
}

但是这个 DrawIcon 示例没有使用 mask ,因此工字梁图标变为白色,并且在白色背景中不可见:

    public void DrawCursorToImage(Image img, Point cursorOffset)
{
if (IconHandle != IntPtr.Zero)
{
Point drawPosition = new Point(Position.X - cursorOffset.X, Position.Y - cursorOffset.Y);

using (Graphics g = Graphics.FromImage(img))
{
g.DrawIcon(Icon.FromHandle(IconHandle), drawPosition.X, drawPosition.Y);
}
}
}

我认为如果我不使用桌面 hdc,那么 DrawIcon 就不会使用 mask 。如何修复 DrawCursorToImage 方法,以便它可以正确使用光标掩码?顺便说一句,我读了这篇文章:C# - Capturing the Mouse cursor image它也没有解决我的问题。感谢您阅读本文。

最佳答案

对 DrawCursorToImage 的修改应该可以使其工作,但我无法真正解释它为什么工作:

public void DrawCursorToImage(Image img, Point cursorOffset)
{
if (IconHandle != IntPtr.Zero)
{
Point drawPosition = new Point(Position.X - cursorOffset.X, Position.Y - cursorOffset.Y);

using (Graphics g = Graphics.FromImage(img))
{
IntPtr hdc = g.GetHdc();
using (Graphics gfx = Graphics.FromHdc(hdc))
{
// For some reason it is necessary to redraw the image here
gfx.DrawImage(img, 0, 0);
gfx.DrawIcon(Icon.FromHandle(IconHandle), drawPosition.X, drawPosition.Y);
}
g.ReleaseHdc();
}
}
}

关于c# - DrawIcon 在绘制图像时不使用光标 mask (I 形光标示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15041970/

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