C# 图形窗口到图像文件
有人知道为什么会一直返回空白图像吗?我找到了这个函数 我将句柄传递给记事本进程/窗口C# 图形窗口到图像文件,c#,.net,windows,image,C#,.net,Windows,Image,有人知道为什么会一直返回空白图像吗?我找到了这个函数 我将句柄传递给记事本进程/窗口 public static Image DrawToBitmap(IntPtr handle) { Bitmap image = new Bitmap(500, 500, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (Graphics graphics = Graphics.FromIma
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的空闲空间!也许我理解错了?尝试将PRF_客户端或PRF_非客户端传递给发送消息的PRF_子级
另外,您是如何导出传递给函数的句柄的?您可以使用
PrintWindow
这是一个样本
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
这可能是权限问题吗?如果您是从VS@Bala R调试,您是以管理员身份运行.exe还是以管理员身份运行visual studio?我使用的是visual studio 2010,我是以管理员身份运行它。我还启动了记事本窗口。我无法让你的代码工作,总是纯黑色输出。但是,.我试过了,当传递
这个时,链接的代码不起作用。Handle
@Chris-我已经在使用它了,但我需要一种不依赖windows UI的方法,即我不能从屏幕上捕获它,它必须通过内存。我只是试过你的建议,但它没有起到令人遗憾的作用。我通过使用Process.GetProcessesByName
和gethandlebywindowtitle namep.MainWindowTitle
来派生句柄。我也尝试过自己启动记事本,并直接控制它,但没有成功。我甚至不知道该试什么!我一直在使用上面的和它最近的工作,但我得到了一些可见的窗口栏和文件菜单的黑色图像,这很奇怪,但这值得一个新的问题。