主窗体的屏幕截图显示子窗体.如何确保子窗体已关闭
本文关键字:窗体 确保 何确保 屏幕截图 显示 | 更新日期: 2023-09-27 18:30:05
我想在Mainform上制作一个Panel的屏幕截图。这个屏幕截图应该在用户在子窗体上选择了一些选项之后制作。一开始一切都很好,但现在屏幕截图包含了子表单的一部分。
子窗体打开如下:
private void Bexport_Click(object sender, EventArgs e) //button
{
ex = new Export();
initexForm();
ex.FormClosed += this.exFormClosed;
ex.TXTfilename.Focus();
ex.ShowDialog(this);
}
制作屏幕截图的功能:
void exFormClosed(object sender, EventArgs e)
{
try
{
System.Drawing.Rectangle bounds = Mainpanel.Bounds;
bounds.Width = bounds.Width - 6;
bounds.Height = bounds.Height - 4;
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(
Mainpanel.PointToScreen(new Point()).X + 3,
Mainpanel.PointToScreen(new Point()).Y + 2, 0,
0, bounds.Size);
}
bitmap.Save(Application.StartupPath + temppic.bmp);
Document doc = new Document();
...
我使用了事件FormClosed
和FormClosing
,它们都具有相似的结果。然后我试图用ex.Hide()
隐藏子窗体,但它隐藏了整个程序,这意味着屏幕截图显示了程序后面的桌面。
有人知道如何在制作屏幕截图之前确保子窗体关闭吗?
Jonathan
问题可能是子窗体关闭后主窗体没有时间重新绘制。
this.Update();
将强制表单重新绘制(http://msdn.microsoft.com/en-us/library/system.windows.forms.control.update.aspx)
您要做的是创建一个与要绘制的控件大小相同的伪表单,然后将控件添加到伪表单中,显示表单并从伪表单中绘制控件。
public Bitmap ControlToBitmap(Control ctrl)
{
Bitmap image = new Bitmap(ctrl.Width, ctrl.Height);
//Create form
Form f = new Form();
//add control to the form
f.Controls.Add(ctrl);
//set the size of the form to the size of the control
f.Size = ctrl.Size;
//draw the control to the bitmap
ctrl.DrawToBitmap(image, new Rectangle(0, 0, ctrl.Width, ctrl.Height));
//dispose the form
f.Dispose();
return image;
}
所以如果你这样称呼它:
void exFormClosed(object sender, EventArgs e)
{
Bitmap bitmap ControlToBitmap(Mainpanel);
bitmap.Save(Application.StartupPath + temppic.bmp);
Document doc = new Document();
...
即使表单已经关闭,这也会起作用。
void exFormClosed(object sender, EventArgs e)
{
try
{
Application.DoEvents();
System.Drawing.Rectangle bounds = Mainpanel.Bounds;
bounds.Width = bounds.Width - 6;
bounds.Height = bounds.Height - 4;
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(
Mainpanel.PointToScreen(new Point()).X + 3,
Mainpanel.PointToScreen(new Point()).Y + 2,
0, 0, bounds.Size);
}