|
|
Title | Save an image of the computer's screen using managed methods in Visual Basic .NET |
Description | This example shows how to save an image of the computer's screen using managed methods in Visual Basic .NET. |
Keywords | graphics, form image, control image, get form image, get control image |
Categories | Graphics |
|
|
The Graphics object's CopyFromScreen method copies some or all of the screen's image to the Graphics object. The follow GetScreenImage method uses CopyFromScreen to grab an image of the screen. The only tricky part is using Screen.PrimaryScreen.Bounds to get the screen's dimensions.
|
|
' Grab the screen's image.
Private Function GetScreenImage() As Bitmap
' Make a bitmap to hold the result.
Dim bm As New Bitmap( _
Screen.PrimaryScreen.Bounds.Width, _
Screen.PrimaryScreen.Bounds.Height, _
PixelFormat.Format24bppRgb)
' Copy the image into the bitmap.
Using gr As Graphics = Graphics.FromImage(bm)
gr.CopyFromScreen( _
Screen.PrimaryScreen.Bounds.X, _
Screen.PrimaryScreen.Bounds.Y, _
0, 0, _
Screen.PrimaryScreen.Bounds.Size, _
CopyPixelOperation.SourceCopy)
End Using
' Return the result.
Return bm
End Function
|
|
(You might need to modify this code if you use multiple monitors. If you do, let me know how it works out.)
The main program is relatively simple.
|
|
' Get the image and save it in a file.
Private Sub btnGetDesktopImage_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnGetDesktopImage.Click
' Hide this form.
Me.Hide()
' Let the user pick a file to hold the image.
If (sfdScreenImage.ShowDialog() = DialogResult.OK) Then
' Make a bitmap to hold the image.
Using bm As Bitmap = GetScreenImage()
' Copy the image into the bitmap.
Using gr As Graphics = Graphics.FromImage(bm)
gr.CopyFromScreen( _
Screen.PrimaryScreen.Bounds.X, _
Screen.PrimaryScreen.Bounds.Left, _
0, 0, _
Screen.PrimaryScreen.Bounds.Size, _
CopyPixelOperation.SourceCopy)
End Using
' Save the bitmap in the selected file.
Dim filename As String = sfdScreenImage.FileName
Dim file_info As New FileInfo(filename)
Select Case (file_info.Extension.ToLower())
Case ".bmp"
bm.Save(filename, ImageFormat.Bmp)
Case ".gif"
bm.Save(filename, ImageFormat.Gif)
Case ".jpg"
Case ".jpeg"
bm.Save(filename, ImageFormat.Jpeg)
Case ".png"
bm.Save(filename, ImageFormat.Png)
Case Else
MessageBox.Show("Unknown file type " & _
file_info.Extension, "Unknown " & _
"Extension", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End Select
End Using
End If
' Show this form again.
Me.Show()
End Sub
|
|
The code hides the program's form (so it doesn't appear in the screen capture). It then displays a save file dialog to let the user select the output file. If the user selects a file, the program uses GetScreenImage to get the screen's image and saves it in a file of the appropriate type.
|
|
|
|
|
|