Snap it! - How to take a screen shot using .NET

程序截图技巧
本文介绍了一种使用.NET Framework的GDI+类库实现程序自动截图的方法。通过设置应用程序为半透明并利用Bitmap和Graphics类,可以捕获屏幕指定区域的快照,并将其保存为多种图片格式。
Introduction

We all would have used snap shots (screen shots) to illustrate bugs or behavior or something that others could understand by seeing them. For taking snap shots we just hit the "Print Screen" key and copy it to Ms Paint and save it. Ever wondered how to programmatically take a snap shot? Then this article is for you.



Image-1 This is how the application looks

Scenario

Why do we need to take snapshots programmatically? Consider a scenario where you want to report some kind of behavior errors in an application. Human supervision is not possible when the occurrence of error is random. So we just code a program to take snap shots at regular intervals and store it as a image file. So that later you can use it.

GDI classes we need to know

Lets see what we need to know before we do coding. We need to have a little knowledge about GDI and graphics classes. The Graphics class provides methods for drawing objects to the display device. A Graphics object is associated with a specific device context. This class is used as a canvas to draw images. In order to display anything in a window, you have to obtain a reference to the window's Graphics object.

Next comes the Bitmap class. A Bitmap object is an object used to work with images defined by pixel data. A bitmap consists of the pixel data for a graphics image and its attributes.

Getting Started


To use the GDI classes we need to include System.Drawing.Imaging namespace in the "using" section of the code. Go to the source view and add a string variable and a property to the class. This string variable is used in the property to store and retrieve the output file name.

// variable to store output file name
private string strFilename;

// Property for storing and retrieving output file name
public string filename
{
    get{return strFilename;}
    set{strFilename=value;}
}
       

In the design view, add a button and a savefiledialog to the form. Double click the button and go to the click event in the code view. Use the savefiledialog control to retrieve the output file name from the user. And store the file name in the variable strFilename using the property filename.

// Check user clicked OK button

// Get the filename and put in the textbox and property

if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)

{

    filename = saveFileDialog1.FileName;

}



Before taking the snap shot we hide our application because we don't want our application in the snap shot image. Sometimes even after hiding the application, the snap shot pictures our application, this is because the application takes few extra milliseconds to hide, so we make our application to wait for some milliseconds.

this.Hide();

// Slow the thread to hide the application before taking the snap

Thread.Sleep(200);



How to Snap It?


Now we create a Bitmap object to set the size of the screen. We use the width and height of the application screen to capture the snap shot. So the user can place our application screen on any area of the screen, move/resize to get the snap shot. To make the user more comfortable in selecting the snap shot area we make the application screen semi-transparent by setting the opacity of the form to 50%.

Resizing the application
Image- 2 Resizing and Moving the screen

// Setting the size of the screen for the bitmap

Bitmap bmp = new Bitmap(this.Width, this.Height, PixelFormat.Format32bppArgb);


           
A Graphics object is required to get the image bounds and create the actual picture. So we initialize a Graphics object and get the image bounds from the Bitmap that we have already created. CopyFromScreen method is used to get the snap shot from the screen. Based on the user selection of the file type in the savefiledialog box,  we use different image formats to save the file using Bitmap.Save function.

// Saving file in the selected image format

bmp.Save(filename, ImageFormat.Jpeg);

After saving the picture we show the application back by using the following statement :

// Showing the application again

this.Show();

           
Viewing the snap shot


Now the screen is captured and the picture is saved. We need to view the snap shot. There is an option available to see how your snap shot has come up, just right after saving the file. We use Process class of System.Diagnostic namespace to view the image file.

// Viewing the image

Process pr = new Process();

pr.StartInfo.FileName = filename;

pr.Start();


             
Viewing the image
Image - 3 Viewing the saved image file

When the Start method is executed the image file is opened in the respective application configured in the system.

Thats all folks.

附上完整的snap代码:
Code
void BtnSnapClick(object sender, System.EventArgs e)
        
{
            
// Check user clicked OK button
            
// Get the filename and put in the textbox and property
            if(saveFileDialog1.ShowDialog()!=DialogResult.Cancel)
            
{
                filename
=saveFileDialog1.FileName;
            }

            
else
                
return;
            
// Check if output file name is selected
            if(filename!=null)
            
{
                
this.Hide();
                
                
// Slow the thread to hide the application before taking the snap
                Thread.Sleep(200);
                
                
// Setting the size of the screen for the bitmap根据窗体的大小来切屏
                
//Bitmap bmp= new Bitmap(Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height,PixelFormat.Format32bppArgb);
                Bitmap bmp= new Bitmap(this.Width,this.Height,PixelFormat.Format32bppArgb);
                
                
// Creating graphic object from the image
                Graphics gr=Graphics.FromImage(bmp);
                
                
// Taking the snapshot
                
//gr.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
                gr.CopyFromScreen(this.Left, this.Top, 00this.Size, CopyPixelOperation.SourceCopy);
                
                
// Saving file in the selected image format
                switch(saveFileDialog1.FilterIndex)
                
{
                    
case 1
                        bmp.Save(filename,ImageFormat.Jpeg);
                        
break;
                    
case 2:
                        bmp.Save(filename,ImageFormat.Png);
                        
break;
                    
case 3:
                        bmp.Save(filename,ImageFormat.Bmp);
                        
break;
                    
case 4:
                        bmp.Save(filename,ImageFormat.Gif);
                        
break;
                    
case 5:
                        bmp.Save(filename,ImageFormat.Icon);
                        
break;
                    
case 6:
                        bmp.Save(filename,ImageFormat.Tiff);
                        
break;
                }

                
                
// Showing the application again
                this.Show();
                
                
// Display success message and prompt the user to see the image
                if(MessageBox.Show("Screen captured successfully! Do you want to see the captured image?","Snap Screen Message", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk)==DialogResult.Yes)
                
{
                    Process pr
= new Process();
                    pr.StartInfo.FileName
=filename;
                    pr.Start();
                }

                
            }

            
else
                MessageBox.Show(
"Please select a file name to save!""Snap Screen Message", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
        
        }

转载于:https://www.cnblogs.com/josephshi/archive/2008/04/24/1168668.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值