Pat*_*ick 1 .net c# compact-framework windows-mobile windows-ce
使用C#,我试图在我的Pocket PC应用程序中绘制一个控件实例,比如一个面板或按钮..NET控件具有漂亮的DrawToBitmap函数,但它在.NET Compact Framework中不存在.
如何在Pocket PC应用程序中将控件绘制到图像?
DrawToBitmap在完整框架中,通过将WM_PRINT消息发送到控件,以及要打印到的位图的设备上下文来工作.Windows CE不包含WM_PRINT,因此这种技术不起作用.
如果正在显示控件,则可以从屏幕复制控件的图像.以下代码使用此方法将兼容DrawToBitmap方法添加到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);
}
}
}
Run Code Online (Sandbox Code Playgroud)