WinForm自动化测试工具开发札记(5)使用.NET Framework 2.0 新功能抓屏
版权声明:原创作品,如需转载,请与作者联系。否则将追究法律责任。 |
花絮
上火了,眼睛疼ing...滴了眼药...看你还敢疼的! 这两天一直在攻克抓屏这一关.手头有几本书,还有网上的一些例子,都是使用Win32 API的BitBlt函数.大同小异.今天在看.NET Framework 2.0的类库时,偶然发现原来抓屏功能已经集成进.NET Framework 2.0的Graphics类了,是个实例方法.两行代码就搞定!下面我给出代码.排在后面的是使用Win32实现的代码,不过已经用处不大了:p
1.使用.NET Framework 2.0 类库新功能:
//==========水之真谛==========//
// // =http://blog.csdn.net/FantasiaX // // //======上善若水,润物无声====// using System; using System.Text; //以下3个using是手动添加的,要想使用System.Drawing,还要添加System.Drawing.dll的引用 using System.Drawing; using System.Drawing.Imaging; using System.Threading; namespace SuperCamera { class Program { static void { //给你5秒钟,摆个Pose! Thread.Sleep(5000); //说:茄~~~~~子~~~~~~ Bitmap photo = new Bitmap(1024, 768, PixelFormat.Format32bppArgb); Graphics graph = Graphics.FromImage(photo); graph.CopyFromScreen(0, 0, 0, 0, new Size(1024, 768)); photo.Save(@"C:\水之真谛.jpg", ImageFormat.Jpeg); Console.WriteLine(@"OK,去C:\盘下面取照片吧!不过,唔~~~不是你的哦!"); Console.ReadLine(); } } } 2.使用Win32 API的:
using System; using System.Text; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Threading; namespace SimpleCamera { class Program { [DllImport("gdi32.dll")] private static extern IntPtr CreateDC(string driver, string device, string win16, IntPtr printDev); [DllImport("gdi32.dll")] private static extern bool BitBlt(IntPtr outputDC, int left, int top, int width, int height, IntPtr sourceDC, int x, int y, int opt); static void { Thread.Sleep(5000); //获取与屏幕相关的DC,并基于此DC生成Graph。 IntPtr screenDC = CreateDC("DISPLAY", null, null, IntPtr.Zero); Graphics screenGraph = Graphics.FromHdc(screenDC); //以屏幕Ghraph为基础,生成位图 Image outputImage = new Bitmap(1024, 768, screenGraph); //获取与位图关联的Graph,并基于此获得位图的DC。 Graphics imgGraph = Graphics.FromImage(outputImage); IntPtr imgDC = imgGraph.GetHdc(); //使用Win32 API "灌图" BitBlt(imgDC, 0, 0, 1024, 768, screenDC, 0, 0, 0xCC0020); //保存位图 imgGraph.ReleaseHdc(imgDC); outputImage.Save(@"C:\水之真谛.jpg", ImageFormat.Jpeg); } } } 此实例再次印证了这样一句话:对类库越了解,就能写出性能越高的程序来。类库的作用就是避免我们自己"从轮子造起"。 法律声明:本文章受到知识产权法保护,任何单位或个人若需要转载此文,必需保证文章的完整性(未经作者许可的任何删节或改动将视为侵权行为)。若您需要转载,请务必注明文章出处为51cto和CSDN以保障网站的权益;请务必注明文章作者为刘铁猛,并向bladey@tom.com发送邮件,标明文章位置及用途。转载时请将此法律声明一并转载,谢谢! 本文出自 “上善若水 润物无声” 博客,转载请与作者联系! 本文出自 51CTO.COM技术博客 |


水之真谛
博客统计信息
热门文章
最新评论
友情链接
