C# 两种方法截取活动窗口屏幕,实现窗体截图

方法1,截屏内容仅包括活动窗口界面,而方法2是从屏幕范围取图,截屏内容会包括屏幕上所有内容。例如有一些程序在桌面顶层显示半透明的悬浮窗,用方法2截屏就会包括这些内容,并不是单纯的活动窗口内容。
方法1,对一些有渐变效果的边框,截图会包括边框范围。方法2则可以把截屏范围限制在程序窗口,截屏范围更准确。

方法1:
1. 获得活动窗口的句柄
2. 根据句柄获得窗口坐标和大小.
3. 指定复制范围,从屏幕复制图像

IntPtr handle = Win32Api.GetForegroundWindow();
Win32Api.RECT rect;
int result = Win32Api.DwmGetWindowAttribute(hwnd, Win32Api.DWMWA_EXTENDED_FRAME_BOUNDS, out rect, Marshal.SizeOf(typeof(Win32Api.RECT)));

int width = rect.Width;
int height = rect.Height;
Bitmap bmp = new Bitmap(width, height);

using (Graphics g = Graphics.FromImage(bmp))
{
    g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size);
}

bmp.Save(screenshotPath, ImageFormat.Png);

方法2:
1. 获得活动窗口的句柄
2. 根据句柄获得 device context (DC) 
3. 从DC复制 bit-block

Win32Api.RECT rect;
Win32Api.GetWindowRect(hwnd, out rect);

Bitmap bmp = new Bitmap(rect.Width, rect.Height);
Graphics g = Graphics.FromImage(bmp);

IntPtr hdcDest = g.GetHdc();
IntPtr hdcSrc = Win32Api.GetWindowDC(hwnd);
Win32Api.BitBlt(hdcDest, 0, 0, rect.Width, rect.Height, hdcSrc, 0, 0, Win32Api.SRCCOPY);
g.ReleaseHdc(hdcDest);
Win32Api.ReleaseDC(hwnd, hdcSrc);
g.Dispose();
bmp.Save(screenshotPath, ImageFormat.Png);

win32 api调用网上都有,这里就不再重复了。

另外,截全屏幕,代码如下 :

public static void SaveFullScreenshot(string path)
        {
            Rectangle bounds = Screen.GetBounds(DrawingPoint.Empty);

            using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.CopyFromScreen(DrawingPoint.Empty, DrawingPoint.Empty, bounds.Size);
                }

                bitmap.Save(path, ImageFormat.Png);
            }
        }

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-10 17:42:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-10 17:42:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-10 17:42:02       87 阅读
  4. Python语言-面向对象

    2024-04-10 17:42:02       96 阅读

热门阅读

  1. 阻止有风险的文件扩展名插件

    2024-04-10 17:42:02       36 阅读
  2. leetcode - 2073. Time Needed to Buy Tickets

    2024-04-10 17:42:02       42 阅读
  3. react ant design 通过函数弹出 modal窗口

    2024-04-10 17:42:02       35 阅读
  4. webRtc生产环境实用方法

    2024-04-10 17:42:02       34 阅读
  5. Linux下的文件权限

    2024-04-10 17:42:02       30 阅读
  6. Fiddler的安装和使用

    2024-04-10 17:42:02       27 阅读
  7. 【C++】深入理解C++命名空间

    2024-04-10 17:42:02       32 阅读
  8. 【iOS ARKit】App 中嵌入 AR Quick Look

    2024-04-10 17:42:02       33 阅读
  9. Python map遍历

    2024-04-10 17:42:02       32 阅读
  10. BERT入门:理解自然语言处理中的基本概念

    2024-04-10 17:42:02       31 阅读
  11. About MATLAB

    2024-04-10 17:42:02       37 阅读
  12. 【鸿蒙NEXT】设置全屏

    2024-04-10 17:42:02       89 阅读