c# - 绘图窗口到图像文件

标签 c# .net windows image

有人知道为什么这会一直返回空白图像吗?我找到了这个功能 here .

我将句柄传递给记事本进程/窗口。

    public static Image DrawToBitmap(IntPtr handle)
    {
        Bitmap image = new Bitmap(500, 500, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        using (Graphics graphics = Graphics.FromImage(image))
        {
            IntPtr hDC = graphics.GetHdc();
            SendMessage(new HandleRef(graphics, handle), WM_PRINT, hDC, PRF_CHILDREN);
            graphics.ReleaseHdc(hDC);
        }
        return image;
    } 

我像这样使用上面的内容:

Image myimage = DrawToBitmap(handle);

myimage.Save("C:\\here.png", ImageFormat.Png);

感谢大家的帮助

更新

我想我已经设法使用以下方法从 SendMessage 获取错误代码:

if (SendMessage(handle, WM_PRINT, hDC, PRF_CLIENT))
{
    Console.WriteLine("Success!");
}
else
{
    Console.WriteLine("Error: " + Marshal.GetLastWin32Error());
}

我收到错误 8,我发现这意味着内存不足?我有超过 500MB 的免费空间!也许我理解错了?

最佳答案

您可以使用 PrintWindow 而不是 SendMessage

这是一个例子

public static Image DrawToBitmap(IntPtr handle)
{
    RECT rect = new RECT();
    GetWindowRect(handle, ref rect);

    Bitmap image = new Bitmap(rect.Right - rect.Left, rect.Bottom - rect.Top);

    using (Graphics graphics = Graphics.FromImage(image))
    {
        IntPtr hDC = graphics.GetHdc();
        PrintWindow(new HandleRef(graphics, handle), hDC, 0);
        graphics.ReleaseHdc(hDC);
    }

    return image;
}

#region Interop

[DllImport("USER32.DLL")]
private static extern bool PrintWindow(HandleRef hwnd, IntPtr hdcBlt, int nFlags);

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);

[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}

#endregion

关于c# - 绘图窗口到图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5696363/

相关文章:

C#:如何判断 EXE 是否有图标?

windows - Windows 是否存在带有标签的程序员的 "document template"?

windows - 集成 Python 时需要匹配多少版本?

c++ - 作为计划任务运行的 .exe 不写入文件

如果隐藏表单有未保存的更改,c# 取消应用程序关闭

c# - 在 .Net 2.0 中读取 PNG 图像文件

c# - 从代码隐藏(或前端)设置 mailto

c# - SpinWait.SpinUntil 的替代方案

c# - .NET Core 自访问查询过滤器

c# - Mono 说证书无效 OpenSSL 说证书有效