如何将win form保存为image / pdf?

时间:2010-02-08 06:43:16

标签: c# winforms

全部, 我确实有一个胜利形式,它就像一台售票机。 我有一个页面,我将获取所有用户信息,然后单击一个名为Generate Bill的按钮将显示一个winform,其中一些图像为ht背景(例如公司徽标名称等),标签控件放置在适当的位置,将显示来自上一表格的信息。如何保存新表格(票证)?

我该怎么做?

1 个答案:

答案 0 :(得分:4)

我的CC.UtilitiesDrawToImage()课程添加了Control扩展方法,可能会对您有所帮助。我会在一秒内发布一些代码片段。

辅助方法:

/// <summary>
/// Captures an <see cref="Image"/> of the specified window
/// </summary>
/// <param name="handle">The handle of the window to capture</param>
/// <returns>An <see cref="Image"/> of the specified window</returns>
public static Image CaptureWindow(IntPtr handle)
{

    IntPtr hdcSrc = User32.GetWindowDC(handle);

    RECT windowRect = new RECT();
    User32.GetWindowRect(handle, windowRect);

    int width = windowRect.right - windowRect.left;
    int height = windowRect.bottom - windowRect.top;

    IntPtr hdcDest = Gdi32.CreateCompatibleDC(hdcSrc);
    IntPtr hBitmap = Gdi32.CreateCompatibleBitmap(hdcSrc, width, height);

    IntPtr hOld = Gdi32.SelectObject(hdcDest, hBitmap);
    Gdi32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, InteropConstants.SRCCOPY);
    Gdi32.SelectObject(hdcDest, hOld);
    Gdi32.DeleteDC(hdcDest);
    User32.ReleaseDC(handle, hdcSrc);

    Image image = Image.FromHbitmap(hBitmap);
    Gdi32.DeleteObject(hBitmap);

    return image;
}

P / Invokes:

[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetWindowRect(IntPtr hWnd, [Out] RECT rect);

[DllImport("gdi32.dll")]
public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjectSource, int nXSrc, int nYSrc, int dwRop);

[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);

[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);

[DllImport("gdi32.dll")]
public static extern bool DeleteDC(IntPtr hDC);

[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);

[StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Auto)]
public class RECT
{
    public int left;
    public int top;
    public int right;
    public int bottom;
}

扩展方法:

/// <summary>
/// Draws the <see cref="Control"/> to an <see cref="Image"/>
/// </summary>
/// <param name="control">The <see cref="Control"/> to draw.</param>
/// <returns>An <see cref="Image"/> of the <see cref="Control"/></returns>
public static Image DrawToImage(this Control control)
{
    return Utilities.CaptureWindow(control.Handle);
}

命名空间与复制/粘贴有点混乱,但如果需要更多,可以查看整个项目,或者这可能足以指向正确的方向。