We have already learned how language like Visual Basic or Delphi implements the capture of 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 , // 驱动名称
string lpszDevice , // 设备名称
string lpszOutput , // 无用,可以设定位"NULL"
IntPtr lpInitData // 任意的打印机数据
) ;
在C#中声明过此API函数,就可以创建和显示器大小一致的位图对象,具体实现语句如下:
IntPtr dc1 = CreateDC ( "DISPLAY" , null , null , ( IntPtr ) null ) ;
//创建显示器的DC
Graphics g1 = Graphics.FromHdc ( dc1 ) ;
//由一个指定设备的句柄创建一个新的Graphics对象
MyImage = new Bitmap ( Screen.PrimaryScreen.Bounds.Width , Screen.PrimaryScreen.Bounds.Height , g1 ) ;
//根据屏幕大小创建一个与之相同大小的Bitmap对象
(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:
//获得屏幕的句柄
IntPtr dc3 = g1.GetHdc ( ) ;
//获得位图的句柄
IntPtr dc2 = g2.GetHdc ( ) ;
//把当前屏幕捕获到位图对象中