Pocket PC: Draw control to bitmap

 ̄綄美尐妖づ 提交于 2019-12-20 05:09:31

问题


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.

How would I go about painting a control to an image in a Pocket PC application?


回答1:


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.

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);
        }
    }
}


来源:https://stackoverflow.com/questions/2292391/pocket-pc-draw-control-to-bitmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!