贝网博客

我的分类
流水记事
源码下载
Asp.net
其它
数据库
Javascript
.Net技术
我的相册
友情链接
博客园
CSDN博客
Start0
最新回复
fasdfasdf
[:..
lz这个东西好厉害,我..
哈哈,好照片
不错,以前一直用黄色..
终于找到支持ff的修正..
终于找到支持ff的修正..
新鲜性
看看,试试,好不好使。
好东西一起学习[:img0..
分类 =》.Net技术
C#截屏代码
发表于:2012-08-10 15:21:54
更新于:2012-10-29 16:32:39

1、使用C#封装好的方法截屏:
Size sz = Screen.PrimaryScreen.Bounds.Size;
int width = sz.Width + 300;// 加300是为了测试双显示器时能否正常截屏
int height = sz.Height;
using (Bitmap bit = new Bitmap(width, height))
using (Graphics g = Graphics.FromImage(bit))
{
    g.CopyFromScreen(this.Location, new Point(0, 0), bit.Size);
    bit.Save(@"c:\b.png");
    g.Dispose();
}

2、调用系统API进行截屏
先定义外部方法:
[DllImport("gdi32.dll")]
static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int
wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, CopyPixelOperation rop);
[DllImport("user32.dll")]
static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDc);
[DllImport("gdi32.dll")]
static extern IntPtr DeleteDC(IntPtr hDc);
[DllImport("gdi32.dll")]
static extern IntPtr DeleteObject(IntPtr hDc);
[DllImport("gdi32.dll")]
static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);
[DllImport("gdi32.dll")]
static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll")]
static extern IntPtr SelectObject(IntPtr hdc, IntPtr bmp);
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr ptr);

然后截屏代码如下:
Size sz = Screen.PrimaryScreen.Bounds.Size;
int width = sz.Width + 300; // 加300是为了测试双显示器时能否正常截屏
int height = sz.Height;

//调用API截屏
IntPtr hDesk = GetDesktopWindow();
IntPtr hSrce = GetWindowDC(hDesk);
IntPtr hDest = CreateCompatibleDC(hSrce);
IntPtr hBmp = CreateCompatibleBitmap(hSrce, width, height);
IntPtr hOldBmp = SelectObject(hDest, hBmp);
if (BitBlt(hDest, 0, 0, width, height, hSrce, 0, 0, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt))
{
    using (Bitmap bmp = Image.FromHbitmap(hBmp))
    {
        SelectObject(hDest, hOldBmp);
        DeleteObject(hBmp);
        DeleteDC(hDest);
        ReleaseDC(hDesk, hSrce);
        bmp.Save(@"c:\a.png");
        bmp.Dispose();
    }
}

发表评论
名称(*):
邮箱:
正文:

©2008 Beinet.cn 版权所有