Mainform的屏幕截图显示了子表单。如何确保子窗体关闭?

时间:2013-09-03 12:26:35

标签: c# windows winforms

我想在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();
            ...

我使用了事件FormClosedFormClosing,两者都有类似的结果。然后我尝试用ex.Hide()隐藏子表单,但它隐藏了整个程序,意味着截图显示了程序后面的桌面。

任何人都知道在制作屏幕截图之前如何确保子窗体已关闭?

乔纳森

3 个答案:

答案 0 :(得分:4)

问题可能是主窗体在子窗体关闭后没有时间重新绘制。

this.Update();

将强制表单重绘(http://msdn.microsoft.com/en-us/library/system.windows.forms.control.update.aspx

答案 1 :(得分:0)

你需要做的是创建一个虚拟表单,它是你想要绘制的控件的大小,然后将控件添加到虚拟表单并显示表单并从虚拟对象中绘制控件。

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();
    ...

即使表格已经关闭,这也会有效。

答案 2 :(得分:0)

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

...