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

方法1,截屏内容仅包括活动窗口界面,而方法2是从屏幕范围取图,截屏内容会包括屏幕上所有内容。例如有一些程序在桌面顶层显示半透明的悬浮窗,用方法2截屏就会包括这些内容,并不是单纯的活动窗口内容。

方法1,对一些有渐变效果的边框,截图会包括边框范围。方法2则可以把截屏范围限制在程序窗口,截屏范围更准确。

方法1:

  1. 获得活动窗口的句柄

  2. 根据句柄获得窗口坐标和大小.

  3. 指定复制范围,从屏幕复制图像

cs 复制代码
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

cs 复制代码
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);

}

}

相关推荐
初九之潜龙勿用2 小时前
C# 解决“因为算法不同,客户端和服务器无法通信”的问题
服务器·开发语言·网络协议·网络安全·c#
net3m335 小时前
C#插件化架构(Plugin Architecture)或 可插拔架构,根据产品类型编码的不同自动路由到目标函数,而无需为每个产品都编码相应的代码!!
重构·c#
水深00安东尼6 小时前
C#猜数字小游戏
开发语言·c#
无风听海8 小时前
.NET10之C# Extension Members深入分析
大数据·c#·.net·extensionmember
唐青枫8 小时前
C#.NET 分布式事务 深入解析:TCC、Saga、Outbox 与落地取舍
c#·.net
人工智能AI技术9 小时前
ML.NET + 1-bit LLM:在 C# 上位机实现仅 1GB 内存的本地 AI 推理
人工智能·c#
cch89189 小时前
PHP vs C#:语言对比与实战选型
开发语言·c#·php
无风听海9 小时前
NET10之C# Primary Constructor 深度指南
开发语言·c#·.net10
余衫马10 小时前
在 IIS 部署 .NET6 WebApi 应用
运维·c#·iis·.net·发布
无风听海10 小时前
.NET10之C# File-Scoped Namespace 深度解析
c#·.net·.net10