TeboScreen: Basic C# Screen Capture Application
源英文文档 <http://www.codeproject.com/KB/cs/TeboScreen.aspx>
翻译:白水 引用请注明出处 <敏捷学院>
源代码下载:http://dev.mjxy.cn/a-CSharp-based-exercises-screen-capture.aspx
Introduction

应用程序抓取屏幕有两种不同的方式:
抓取屏幕:抓取整个屏幕,然后将图像保存到指定的图片文件中。
抓取区域:用户按住鼠标左键,绘制一个矩形,指定他们希望捕捉屏幕的一部分。在释放鼠标左键,然后指定一个文件名将扑捉到的矩形图像保存到指定的文件中。
背景
这个应用程序是我一个C#学习的练习。我想看看使用C#如何简单的创建一个屏幕保存 程序,最后我花了一个下午的时间写应用程序。
我决定使用一个简单的方式来解决如何让用户在屏幕上画一个矩形。最大化应用程序窗口,并使它透明度为30%。先绘制一个矩形,然后使用窗体背景色绘制一个矩形用来擦出以前的矩形。由于窗体是最大化的,任何坐标位置正好对应屏幕上的坐标。ScreenShot.CaptureImage方法绘制矩形并返回矩形的坐标。
代码分析
两个模块实现屏幕抓取
Capture Screen
我们需要做的就是将屏幕的区域传递给ScreenShot.CaptureImage方法。这里唯一需要注意的地方就是我们暂停了250毫秒,让屏幕重绘。如果不这样做,直接执行下一行代码,我们应用程序的本身也会被扑捉到。
5 |
System.Threading.Thread.Sleep(250); |
7 |
Rectangle bounds = Screen.GetBounds(Screen.GetBounds(Point.Empty)); |
9 |
ScreenShot.CaptureImage(Point.Empty, Point.Empty, bounds, ScreenPath); |
捕抓一个区域
用户按住鼠标左键,绘制一个矩形,指定他们希望捕捉屏幕的一部分。在释放鼠标左键,然后指定一个文件名将扑捉到的矩形图像保存到指定的文件中。mouse_Move事件用来擦除之前绘制的矩形。
01 |
private void mouse_Move(object sender, MouseEventArgs e) |
07 |
mouse button is held down |
15 |
g.DrawRectangle(EraserPen, CurrentTopLeft.X, CurrentTopLeft.Y,CurrentBottomRight.X - CurrentTopLeft.X, CurrentBottomRight.Y - |
21 |
if (Cursor.Position.X < ClickPoint.X) |
25 |
CurrentTopLeft.X = Cursor.Position.X; |
27 |
CurrentBottomRight.X = ClickPoint.X; |
35 |
CurrentTopLeft.X = ClickPoint.X; |
37 |
CurrentBottomRight.X = Cursor.Position.X; |
43 |
if (Cursor.Position.Y < ClickPoint.Y) |
47 |
CurrentTopLeft.Y = Cursor.Position.Y; |
49 |
CurrentBottomRight.Y = ClickPoint.Y; |
57 |
CurrentTopLeft.Y = ClickPoint.Y; |
59 |
CurrentBottomRight.Y = Cursor.Position.Y; |
65 |
g.DrawRectangle(MyPen, CurrentTopLeft.X, CurrentTopLeft.Y,CurrentBottomRight.X - CurrentTopLeft.X, CurrentBottomRight.Y - CurrentTopLeft.Y); |
这里是调用ScreenShot.CaptureImage如何捕抓一个区域。
1 |
Point StartPoint = new Point(ClickPoint.X, ClickPoint.Y); |
2 |
Rectangle bounds = new Rectangle(ClickPoint.X, ClickPoint.Y, CurrentPoint.X - ClickPoint.X, CurrentPoint.Y - ClickPoint.Y); |
3 |
ScreenShot.CaptureImage(StartPoint, Point.Empty, bounds, ScreenPath); |
捕抓屏幕的代码定义在类ScreenShot中,包含一个静态的方法CaptureImage。
05 |
public static void CaptureImage(Point SourcePoint, Point DestinationPoint, |
07 |
Rectangle SelectionRectangle, string FilePath) |
11 |
using (Bitmap bitmap = new Bitmap(SelectionRectangle.Width, |
13 |
SelectionRectangle.Height)) |
17 |
using (Graphics g = Graphics.FromImage(bitmap)) |
21 |
g.CopyFromScreen(SourcePoint, DestinationPoint, |
23 |
SelectionRectangle.Size); |
27 |
bitmap.Save(FilePath, ImageFormat.Bmp); |