Make a screen capture program with C #

Source: Internet
Author: User
Tags array bool implement win32
Program we have learned how language like Visual Basic or Delphi can be implemented to capture screen images. So how do you implement this functionality for C #? This article is to explore this issue.

A Program Design Development and operating environment:

(1). Microsoft Windows 2000 Server Edition

(2). Net FrameWork SDK Beta 2

Two The key steps of program design and the specific implementation methods:

(1). First, create a bitmap object that is the same size as the current screen:

To do this, you first need to get the DC for the current monitor, and then create the graphic object based on the DC, and then the graphic object is generated. This produces a bitmap object that is consistent with the current screen size. Because to get the DC for the monitor, use. NET's class library is not achievable, which requires invoking a Windows API function. We know that Windows all APIs are encapsulated in files in the "Kernel", "User" and "GDI" Three libraries: "Kernel", and his library name is "KERNEL32." DLL ". The class library "User" is called "USER32" in the Win32. DLL ". It mainly manages the entire user interface. For example: Windows, menus, dialog boxes, icons, and so on. "GDI" (Image Device Interface), which is named "GDI32.dll" in Win32, is encapsulated in this class library to obtain a DC for the monitor, and the API function called--CREATEDC (). The API functions to declare windows in C # need to use the namespace "System.Runtime.InteropServices" in the. Net FrameWork SDK, which provides a series of classes to access COM objects and invokes local API functions. Here is a declaration of this function in C #:

[System.Runtime.InteropServices.DllImportAttribute ("Gdi32.dll")]
private static extern IntPtr CreateDC (
String lpszdriver,//driver name
String lpszdevice,//device name
String lpszoutput,//useless, can be set to locate "NULL"
INTPTR Lpinitdata//Any printer data
) ;
By declaring this API function in C #, you can create a bitmap object that is the same size as the display, with the following implementation statements:
INTPTR DC1 = CreateDC ("DISPLAY", NULL, NULL, (INTPTR) null);
To create a DC for the monitor
Graphics G1 = GRAPHICS.FROMHDC (DC1);
Creates a new graphics object from the handle of a specified device
MyImage = new Bitmap (Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, G1);
Create a Bitmap object of the same size based on the screen size

(2). Create a graphic object that is the same as this bitmap:

This functionality can be achieved by following the code:

Graphics g2 = Graphics.fromimage (myimage);

(3). Get the handle of the current screen and bitmap:

The handle to this two object is for the next step to capture the current screen image, and the method implemented in the program is to capture the current screen into a bitmap object that has already been created. The specific implementation code is as follows:

Get the handle to the screen
IntPtr DC3 = G1. GetHdc ();
Get a handle to a bitmap
IntPtr DC2 = G2. GetHdc ();
Capture the current screen into the bitmap object

(4). Capture the current screen:

We do this by saving the current screen to the created bitmap object, which is--bitblt through an API function in Windows. I think most programmers are not unfamiliar with this API function, because in Windows image programming, this function is used in many places. This API function, like the API function described above, is also encapsulated in "GDI32.dll", following the declaration of this function in C #:

[System.Runtime.InteropServices.DllImportAttribute ("Gdi32.dll")]
private static extern bool BitBlt (
IntPtr hdcdest,//handle of target device
int nxdest,//x coordinate of the upper-left corner of the target object
int nydest,//x coordinate of the upper-left corner of the target object
int nwidth,//The width of the rectangle of the target object
int nheight,//The length of the rectangle of the target object
IntPtr hdcsrc,//source device handle
int NXSRC,//x coordinate of the upper-left corner of the source object
int NYSRC,//x coordinate of the upper-left corner of the source object
System.Int32 Dwrop//Raster operating values
) ;
Knowing this statement enables you to save the current screen as follows:
BitBlt (DC2, 0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, DC3, 0, 0, 13369376);

(5). Save the current screen to your hard disk and release the handle:

G1. RELEASEHDC (DC3);
Release screen handle
G2. RELEASEHDC (DC2);
Releasing a bitmap handle
Myimage.save ("C:\\myjpeg.jpg", imageformat.jpeg);

We can save the current screen in a different file format according to our own requirements. The program described in this article is saved as a "JPG" file, and you can change the file type saved to your hard disk by modifying the second argument of the "save" method, for example, if the second argument is " Imageformat.gif ", then you save the file to the hard disk as" Gif "file. For other file formats, you can refer to the. Net FrameWork SDK, which is described in detail.

Three Use C # to do screen capture program code and run programs:

After mastering these important steps, you can get the source code (Capture.cs) of the screen Capture program in C #, as follows:

Using System;
Using System.Drawing;
Using System.Collections;
Using System.ComponentModel;
Using System.Windows.Forms;
Using System.Data;
Using System.Drawing.Imaging;
Using System.IO;
Import namespaces that are used in programs
public class Capture:form
{
Private System.ComponentModel.Container components = null;
Private icon Mnettrayicon = new icon ("Tray.ico");
Private Bitmap myimage = null;
Private NotifyIcon TrayIcon;
Private ContextMenu notifyiconmnu;
Public Capture ()
{
Initializing the components used in a form
InitializeComponent ();
}
protected override void Onactivated (EventArgs e)
{
This. Hide ();
}
[System.Runtime.InteropServices.DllImportAttribute ("Gdi32.dll")]
private static extern bool BitBlt (
IntPtr hdcdest,//handle of target device
int nxdest,//x coordinate of the upper-left corner of the target object
int nydest,//x coordinate of the upper-left corner of the target object
int nwidth,//The width of the rectangle of the target object
int nheight,//The length of the rectangle of the target object
IntPtr hdcsrc,//source device handle
int NXSRC,//x coordinate of the upper-left corner of the source object
int NYSRC,//x coordinate of the upper-left corner of the source object
System.Int32 Dwrop//Raster operating values
) ;

[System.Runtime.InteropServices.DllImportAttribute ("Gdi32.dll")]
private static extern IntPtr CreateDC (
String lpszdriver,//driver name
String lpszdevice,//device name
String lpszoutput,//useless, can be set to locate "NULL"
INTPTR Lpinitdata//Any printer data
) ;
public void capture (object sender, System.EventArgs e)
{
This. Visible = false;
INTPTR DC1 = CreateDC ("DISPLAY", NULL, NULL, (INTPTR) null);
To create a DC for the monitor
Graphics G1 = GRAPHICS.FROMHDC (DC1);
Creates a new graphics object from the handle of a specified device
MyImage = new Bitmap (Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, G1);
Create a Bitmap object of the same size based on the screen size
Graphics g2 = Graphics.fromimage (myimage);
Get the handle to the screen
IntPtr DC3 = G1. GetHdc ();
Get a handle to a bitmap
IntPtr DC2 = G2. GetHdc ();
Capture the current screen into the bitmap object
BitBlt (DC2, 0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, DC3, 0, 0, 13369376);
Put the current screen copy into place in the diagram
G1. RELEASEHDC (DC3);
Release screen handle
G2. RELEASEHDC (DC2);
Releasing a bitmap handle
Myimage.save ("C:\\myjpeg.jpg", imageformat.jpeg);
MessageBox.Show ("The current screen has been saved to the c:\\myjpeg.jpg file!") " ) ;
This. Visible = true;
}
public void Exitselect (object sender, System.EventArgs e)
{
Hide icons in a tray program
Trayicon.visible = false;
Shutting down the system
This. Close ();
}
To purge resources used in a program
public override void Dispose ()
{
Base. Dispose ();
if (Components!= null)
Components. Dispose ();
}
private void InitializeComponent ()
{
Set the various properties of the pallet program
TrayIcon = new NotifyIcon ();
Trayicon.icon = Mnettrayicon;
Trayicon.text = "Use C # to do screen capture program";
Trayicon.visible = true;
Defines a MenuItem array and assigns the array to the ContextMenu object at the same time
MenuItem [] Mnuitms = new MenuItem [3];
MNUITMS [0] = new MenuItem ();
MNUITMS [0]. Text = "Capture the current screen!" " ;
MNUITMS [0]. Click + + new System.EventHandler (this.capture);
MNUITMS [1] = new MenuItem ("-");
MNUITMS [2] = new MenuItem ();
MNUITMS [2]. Text = "Exit system";
MNUITMS [2]. Click + + new System.EventHandler (this. Exitselect);
MNUITMS [2]. Defaultitem = true;
Notifyiconmnu = new ContextMenu (MNUITMS);
Trayicon.contextmenu = Notifyiconmnu;
Add a set of ContextMenu objects for the tray program
This. SuspendLayout ();
This. AutoScaleBaseSize = new System.Drawing.Size (5, 13);
This. ClientSize = new System.Drawing.Size (320, 56);
This. ControlBox = false;
This. MaximizeBox = false;
This. MinimizeBox = false;
This. WindowState = System.Windows.Forms.FormWindowState.Minimized;
This. Name = "Capture";
This. ShowInTaskbar = false;
This. Text = "Use C # to do screen capture program!" " ;
This. ResumeLayout (FALSE);
}
static void Main ()
{
Application.Run (New Capture ());
}
}





Four Summarize:

Although the. Net FrameWork SDK is rich in content and the functionality that he can implement is powerful, some low-level operations can sometimes be implemented using Windows API functions, and screen The key to capture is to master the method of calling API functions in C #. Hopefully, this article will help you with your mastery of API programming in C #.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.