关于有窗口句柄和无窗口句柄的截图

C#里面提供了CopyFromScreen的函数,可以方便地实现屏幕截图,然而这只是针对有窗口句柄的的,像迅雷7、wpf等无句柄窗口是无法截取的,代码如下,可以试一下:

//不用Dll切图,但是会切不到悬浮窗口
private Bitmap CutImageWithoutDll()
{
	int width = Screen.PrimaryScreen.Bounds.Width;
	int height = Screen.PrimaryScreen.Bounds.Height;
	Bitmap bmp = new Bitmap(width, height);
	using (Graphics g = Graphics.FromImage(bmp))
	{
		g.CopyFromScreen(0, 0, 0, 0, new Size(width, height),CopyPixelOperation.SourceCopy);
	}
	return bmp;
}


然而如果要实现悬浮窗口的截图呢?目前我是用到api,网上的方法都比较复杂,而我的如下,个人觉得比较简单的,如有的话,可以提出来,代码如下,希望对有需要的人有帮助吧:

[DllImport("Gdi32.dll")]
public extern static int BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);
//Dll切图,可以截取全部窗口
private void CutImageWithDll()
{
	int width = Screen.PrimaryScreen.Bounds.Width;
	int height = Screen.PrimaryScreen.Bounds.Height;
	Bitmap screenCopy = new Bitmap(width, height);
	using (Graphics gDest = Graphics.FromImage(screenCopy))
	{
		Graphics gSrc = Graphics.FromHwnd(IntPtr.Zero);
		IntPtr hSrcDC = gSrc.GetHdc();
		IntPtr hDC = gDest.GetHdc();
		int retval = BitBlt(hDC,0,0,width,height,hSrcDC,0,0,(int)(CopyPixelOperation.SourceCopy|CopyPixelOperation.CaptureBlt));
		gDest.ReleaseHdc();
		gSrc.ReleaseHdc();
	}
}

对比一下,几乎可以认为C#的CopyFromScreen封装了第二种方法调用的API,只是最后一个参数给设定成了枚举值,且是不能与和或的枚举,使得不能同时实现两种参数设置。

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值