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

时间:2022-04-25 15:25:22

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,只是最后一个参数给设定成了枚举值,且是不能与和或的枚举,使得不能同时实现两种参数设置。