Programmatically Capturing and Saving Screenshots as Bitmaps
Integrating screen capture functionality directly into your application offers a streamlined alternative to manual screenshotting. This article details a method for achieving this using C#.
Utilizing Graphics.CopyFromScreen()
The core function for screen capture is Graphics.CopyFromScreen()
. This method efficiently copies a defined screen area into a Bitmap object. The implementation is as follows:
<code class="language-csharp">// Create a Bitmap matching the primary screen's dimensions. Bitmap bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); // Create a Graphics object from the Bitmap. Graphics gfxScreenshot = Graphics.FromImage(bmpScreenshot); // Capture the entire screen. gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); // Save the screenshot (e.g., as a PNG). bmpScreenshot.Save("Screenshot.png", ImageFormat.Png); </code>
This code first creates a Bitmap with dimensions matching the primary screen. A Graphics object is then created from this Bitmap. CopyFromScreen()
copies the screen's contents into the Bitmap. Finally, the Bitmap is saved to a file, here using the PNG format. This process allows for programmatic manipulation of the captured image within your application.
The above is the detailed content of How Can I Capture and Save a Screenshot as a Bitmap in My Application?. For more information, please follow other related articles on the PHP Chinese website!