使用C#,我试图绘制控件的一个实例,说面板或按钮,位图在我的Pocket PC应用程序。 .NET控件有漂亮的DrawToBitmap功能,但它不能在.NET Compact Framework的存在。
Using C#, I'm trying to draw an instance of a control, say a panel or button, to a bitmap in my Pocket PC application. .NET controls has the nifty DrawToBitmap function, but it does not exist in .NET Compact Framework.
我如何去画一个控件的图像中的Pocket PC应用程序?
How would I go about painting a control to an image in a Pocket PC application?
DrawToBitmap
在全框架的工作原理是发送的 WM_PRINT
消息控制,随着一个设备上下文位图打印。 Windows CE不包括 WM_PRINT
,所以这种技术将无法工作。
DrawToBitmap
in the full framework works by sending the WM_PRINT
message to the control, along with the device context of a bitmap to print to. Windows CE doesn't include WM_PRINT
, so this technique won't work.
如果显示您的控件,您可以复制从屏幕控制的图像。下面code使用这种方法来兼容 DrawToBitmap
方法添加到控制
:
If your control is being displayed, you can copy the image of the control from the screen. The following code uses this approach to add a compatible DrawToBitmap
method to Control
:
public static class ControlExtensions
{
[DllImport("coredll.dll")]
private static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("coredll.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("coredll.dll")]
private static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest,
int nWidth, int nHeight, IntPtr hdcSrc,
int nXSrc, int nYSrc, uint dwRop);
private const uint SRCCOPY = 0xCC0020;
public static void DrawToBitmap(this Control control, Bitmap bitmap,
Rectangle targetBounds)
{
var width = Math.Min(control.Width, targetBounds.Width);
var height = Math.Min(control.Height, targetBounds.Height);
var hdcControl = GetWindowDC(control.Handle);
if (hdcControl == IntPtr.Zero)
{
throw new InvalidOperationException(
"Could not get a device context for the control.");
}
try
{
using (var graphics = Graphics.FromImage(bitmap))
{
var hdc = graphics.GetHdc();
try
{
BitBlt(hdc, targetBounds.Left, targetBounds.Top,
width, height, hdcControl, 0, 0, SRCCOPY);
}
finally
{
graphics.ReleaseHdc(hdc);
}
}
}
finally
{
ReleaseDC(control.Handle, hdcControl);
}
}
}