gpt4 book ai didi

C# Windows 窗体控件到图像?

转载 作者:太空狗 更新时间:2023-10-30 00:36:27 25 4
gpt4 key购买 nike

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

我使用的代码类似于 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com