C# print screen active window

萝らか妹 提交于 2019-12-19 10:33:25

问题


I am currently trying to print screen an active window using Visual C#. I have this code:

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

But this code captures the SaveImageDialog as well. Any cure to this problem? Thanks a lot.


回答1:


The simplest way will be to switch the code:

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

First create the screenshot and than show the save dialog and save it to the disc if the dialog was closed with OK.

The problem is, that in your code, the program has no time to repaint your form. If you want to retain the structure of your code, you would need to give it some time to process the pending events, possibly by calling Application.DoEvents.



来源:https://stackoverflow.com/questions/5336553/c-sharp-print-screen-active-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!