C# Windows 窗体控件到图像?

标签 c# winforms graphics

我正在尝试创建一个面板的图像并将其保存到一个文件夹中。问题是面板有滚动条,生成的图像仅用于面板的可见部分。

我使用的代码类似于 Panel.DrawToImage。是否有任何帮助可以将整个面板保存为图片,而不仅仅是可见部分?

最佳答案

我认为 WM_PRINT 消息会有所帮助。这是一个几乎 有效的示例。 (它仍然会自己打印滚动条,并且在“滚动条外”部分会丢失背景。)也许您可以尝试一下并让它正常工作,或者具有更多 WinForms 经验的人可以将其提升到一个新的水平?

在您的类中声明以下内容:

[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

private const int WM_PRINT = 791;

/// <summary>
/// The WM_PRINT drawing options
/// </summary>
[Flags]
private enum DrawingOptions
{
    /// <summary>
    /// Draws the window only if it is visible.
    /// </summary>
    PRF_CHECKVISIBLE = 1,

    /// <summary>
    /// Draws the nonclient area of the window.
    /// </summary>
    PRF_NONCLIENT = 2,
    /// <summary>

    /// Draws the client area of the window.
    /// </summary>
    PRF_CLIENT = 4,

    /// <summary>
    /// Erases the background before drawing the window.
    /// </summary>
    PRF_ERASEBKGND = 8,

    /// <summary>
    /// Draws all visible children windows.
    /// </summary>
    PRF_CHILDREN = 16,

    /// <summary>
    /// Draws all owned windows.
    /// </summary>
    PRF_OWNED = 32
}

然后,将控件绘制为位图:

using (Bitmap screenshot = new Bitmap(this.panel1.DisplayRectangle.Width, this.panel1.DisplayRectangle.Height))
using (Graphics g = Graphics.FromImage(screenshot))
{
    try
    {
        SendMessage(this.panel1.Handle, WM_PRINT, g.GetHdc().ToInt32(), (int)(DrawingOptions.PRF_CHILDREN | DrawingOptions.PRF_CLIENT | DrawingOptions.PRF_NONCLIENT | DrawingOptions.PRF_OWNED));
    }
    finally
    {
        g.ReleaseHdc();
    }
    screenshot.Save("temp.bmp");
}

编辑:这里有一个替代的绘画策略,可能会让您得到您正在寻找的东西。我正在做一些假设,但也许它会起作用。它首先在 Bitmap 上绘制一个虚拟背景,然后删除滚动条:

using (Bitmap screenshot = new Bitmap(this.panel1.DisplayRectangle.Width, this.panel1.DisplayRectangle.Height))
using (Graphics g = Graphics.FromImage(screenshot))
{
    g.FillRectangle(SystemBrushes.Control, 0, 0, screenshot.Width, screenshot.Height);
    try
    {
        SendMessage(this.panel1.Handle, WM_PRINT, g.GetHdc().ToInt32(), (int)(DrawingOptions.PRF_CHILDREN | DrawingOptions.PRF_CLIENT | DrawingOptions.PRF_OWNED));
    }
    finally
    {
        g.ReleaseHdc();
    }
    screenshot.Save("temp.bmp");
}

关于C# Windows 窗体控件到图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1881317/

相关文章:

c# - 强制 double 保留四位小数

winforms - 当焦点位于特定文本框中时,如何显示工具提示?

c# - RichTextBox换行转换?

winforms - 如何禁用桌面和/或任务栏

javascript - 有没有更有效的方法来设置 p5.graphics 像素数组等于另一个使用 JavaScript 中的 p5.js ?

opengl - 如何绘制立方体而不是四边形?

c# - Windows Phone 7.1 + Azure WebRole 中的错误处理/报告

c# - BlockingSenderDestination.sendReceive() UTF-8 问题

c# - 如何在 C# 中有效地获取字节数组的子集(前 N 个元素)?

opengl - 手动深度渲染: Random results despite using atomic operations