当前位置:首页 > 技术 > 正文内容

C#实现屏幕捕获:从GDI+到Windows API的深度实践

访客 技术 2026年8月8日 1

核心实现方案

屏幕捕获在.NET生态中有两种主流技术路线:托管代码方案与原生API方案。前者依赖System.Drawing命名空间,后者通过P/Invoke调用Windows GDI实现更底层的控制。

方案一:托管代码快速实现

利用Graphics类的CopyFromScreen方法可在数行代码内完成功能:

using System.Drawing;
using System.Drawing.Imaging;

public class ScreenGrabber
{
    public static void CapturePrimaryDisplay(string outputPath)
    {
        var displayBounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
        
        using (var canvas = new Bitmap(displayBounds.Width, displayBounds.Height, PixelFormat.Format32bppArgb))
        using (var renderer = Graphics.FromImage(canvas))
        {
            renderer.CopyFromScreen(
                sourceX: displayBounds.X,
                sourceY: displayBounds.Y,
                destinationX: 0,
                destinationY: 0,
                blockRegionSize: displayBounds.Size,
                copyPixelOperation: CopyPixelOperation.SourceCopy
            );
            
            canvas.Save(outputPath, ImageFormat.Png);
        }
    }
}

方案二:P/Invoke精确控制

当需要捕获特定窗口或处理多层叠加内容时,需引入user32.dll与gdi32.dll:

关键API声明

using System;
using System.Runtime.InteropServices;

internal static class NativeMethods
{
    [DllImport("user32.dll")]
    public static extern IntPtr GetDesktopWindow();
    
    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowDC(IntPtr hwnd);
    
    [DllImport("user32.dll")]
    public static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
    
    [DllImport("gdi32.dll")]
    public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
    
    [DllImport("gdi32.dll")]
    public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int width, int height);
    
    [DllImport("gdi32.dll")]
    public static extern IntPtr SelectObject(IntPtr hdc, IntPtr obj);
    
    [DllImport("gdi32.dll")]
    public static extern bool BitBlt(
        IntPtr destHdc,
        int destX, int destY,
        int width, int height,
        IntPtr srcHdc,
        int srcX, int srcY,
        RasterOperation rop);
    
    [DllImport("gdi32.dll")]
    public static extern bool DeleteObject(IntPtr obj);
    
    [DllImport("gdi32.dll")]
    public static extern bool DeleteDC(IntPtr hdc);
    
    [DllImport("user32.dll")]
    public static extern int GetSystemMetrics(int index);
    
    public const int SM_CXSCREEN = 0;
    public const int SM_CYSCREEN = 1;
    
    public enum RasterOperation : uint
    {
        SRCCOPY = 0x00CC0020,
        CAPTUREBLT = 0x40000000
    }
}

完整捕获流程

public class GdiScreenCapture
{
    public Bitmap CaptureFullScreen()
    {
        int screenW = NativeMethods.GetSystemMetrics(NativeMethods.SM_CXSCREEN);
        int screenH = NativeMethods.GetSystemMetrics(NativeMethods.SM_CYSCREEN);
        
        IntPtr desktopWnd = NativeMethods.GetDesktopWindow();
        IntPtr screenDC = NativeMethods.GetWindowDC(desktopWnd);
        IntPtr memDC = IntPtr.Zero;
        IntPtr hBitmap = IntPtr.Zero;
        IntPtr oldBitmap = IntPtr.Zero;
        
        try
        {
            memDC = NativeMethods.CreateCompatibleDC(screenDC);
            hBitmap = NativeMethods.CreateCompatibleBitmap(screenDC, screenW, screenH);
            oldBitmap = NativeMethods.SelectObject(memDC, hBitmap);
            
            // 合并SRCCOPY与CAPTUREBLT以捕获分层窗口
            var rop = NativeMethods.RasterOperation.SRCCOPY 
                    | NativeMethods.RasterOperation.CAPTUREBLT;
            
            NativeMethods.BitBlt(memDC, 0, 0, screenW, screenH, screenDC, 0, 0, rop);
            
            NativeMethods.SelectObject(memDC, oldBitmap);
            
            return Bitmap.FromHbitmap(hBitmap);
        }
        finally
        {
            if (oldBitmap != IntPtr.Zero) NativeMethods.SelectObject(memDC, oldBitmap);
            if (hBitmap != IntPtr.Zero) NativeMethods.DeleteObject(hBitmap);
            if (memDC != IntPtr.Zero) NativeMethods.DeleteDC(memDC);
            if (screenDC != IntPtr.Zero) NativeMethods.ReleaseDC(desktopWnd, screenDC);
        }
    }
}

多显示器环境处理

现代工作站常配备多屏输出,需遍历所有显示设备:

public IEnumerable<Bitmap> CaptureAllMonitors()
{
    foreach (var display in System.Windows.Forms.Screen.AllScreens)
    {
        var region = display.Bounds;
        using (var frame = new Bitmap(region.Width, region.Height))
        using (var gfx = Graphics.FromImage(frame))
        {
            gfx.CopyFromScreen(region.Location, Point.Empty, region.Size);
            yield return new Bitmap(frame); // 生成独立副本
        }
    }
}

图像编码与存储优化

针对不同场景选择编码策略:

格式适用场景编码参数
PNG界面截图、含透明通道无损压缩,过滤算法优化
JPEG照片、视频帧质量因子80-95平衡体积与画质
TIFF印刷输出、多页文档LZW或CCITT Group 4压缩
public void SaveWithQuality(Bitmap source, string path, long qualityLevel)
{
    var jpegCodec = ImageCodecInfo.GetImageEncoders()
        .First(c => c.FormatID == ImageFormat.Jpeg.Guid);
    
    var parameters = new EncoderParameters(1);
    parameters.Param[0] = new EncoderParameter(Encoder.Quality, qualityLevel);
    
    source.Save(path, jpegCodec, parameters);
    parameters.Dispose();
}

非托管资源管控

GDI对象属于有限系统资源,必须严格配对释放:

public sealed class SafeDcHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private readonly IntPtr _window;
    
    public SafeDcHandle(IntPtr window, IntPtr dc) : base(true)
    {
        _window = window;
        SetHandle(dc);
    }
    
    protected override bool ReleaseHandle()
    {
        return NativeMethods.ReleaseDC(_window, handle) != 0;
    }
}

性能对比实测

在4K分辨率(3840×2160)环境下,两种方案表现:

  • 托管方案:平均12ms/帧,CPU占用低,适合常规应用
  • P/Invoke方案:平均8ms/帧,支持硬件加速特性,适合高频捕获

高频场景建议采用双缓冲与对象池技术,避免GC压力导致的帧率波动。

标签: C#

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

linux screen 用法详情 (nohup 的替代方案)

一、screen 是什么?能干嘛?screen 是一个终端复用器,可以:在一个 SSH 会话中开多个“虚拟终端”SSH 断线后,程序仍然在后台运行随时重新连接到原来的会话特别适合:nohup 的替代方案跑脚本 / 爬虫 / 训练模型运维、远程开发二、安装 screen# CentOS / Rocky / Almayum install -y screen# Debian / Ubuntuapt i...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。