C#打印屏幕活动窗口

时间:2011-03-17 08:22:00

标签: c# printing window screen

我目前正在尝试使用Visual C#打印一个活动窗口。我有这段代码:

SaveFileDialog saveImageDialog = new SaveFileDialog();
saveImageDialog.Title = "Select output file:";
saveImageDialog.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
//saveImageDialog.FileName = printFileName;
if (saveImageDialog.ShowDialog() == DialogResult.OK)
{
    // Set the bitmap object to the size of the screen
    bmpScreenshot = new Bitmap(this.Bounds.Width, this.Bounds.Height, PixelFormat.Format32bppArgb);
    // Create a graphics object from the bitmap
    gfxScreenshot = Graphics.FromImage(bmpScreenshot);
    // Take the screenshot from the upper left corner to the right bottom corner
    gfxScreenshot.CopyFromScreen(this.Bounds.X, this.Bounds.Y, 0, 0, this.Bounds.Size, CopyPixelOperation.SourceCopy);
    // Save the screenshot to the specified path that the user has chosen
    bmpScreenshot.Save(saveImageDialog.FileName, ImageFormat.Png);
}

但是这段代码也捕获了SaveImageDialog。有什么办法解决这个问题?非常感谢。

1 个答案:

答案 0 :(得分:4)

最简单的方法是切换代码:

// Set the bitmap object to the size of the screen
bmpScreenshot = new Bitmap(this.Bounds.Width, this.Bounds.Height,
                           PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap
gfxScreenshot = Graphics.FromImage(bmpScreenshot);
// Take the screenshot from the upper left corner to the right bottom corner
gfxScreenshot.CopyFromScreen(this.Bounds.X, this.Bounds.Y, 0, 0,
                             this.Bounds.Size, CopyPixelOperation.SourceCopy);

SaveFileDialog saveImageDialog = new SaveFileDialog();
saveImageDialog.Title = "Select output file:";
saveImageDialog.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
//saveImageDialog.FileName = printFileName;
if (saveImageDialog.ShowDialog() == DialogResult.OK)
{
    // Save the screenshot to the specified path that the user has chosen
    bmpScreenshot.Save(saveImageDialog.FileName, ImageFormat.Png);
}

首先创建屏幕截图,然后显示保存对话框,如果对话框已关闭,则将其保存到光盘。

问题是,在您的代码中,程序没有时间重新绘制表单。如果要保留代码的结构,则需要给它一些时间来处理待处理事件,可能需要调用Application.DoEvents