加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将窗口绘制到图像文件

发布时间:2020-12-15 17:16:15 所属栏目:百科 来源:网络整理
导读:任何人都知道为什么这会一直返回空白图像?我发现这个功能 here. 我将句柄传递给记事本进程/窗口. public static Image DrawToBitmap(IntPtr handle) { Bitmap image = new Bitmap(500,500,System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (Gra
任何人都知道为什么这会一直返回空白图像?我发现这个功能 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,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,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读