c# 根据句柄截取指定窗口的图片并保存 我要完整代码
时间: 2024-09-21 14:01:39 浏览: 76
在 C# 中,你可以使用 `Windows Presentation Foundation` (WPF) 和 `InteropServices` 来截取 Windows 窗口的图片并保存到文件。这里是一个基本示例,展示如何通过句柄获取窗口的屏幕截图:
```csharp
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Interop;
namespace CaptureWindowImage
{
public class WindowCapture
{
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string className, string windowText);
[DllImport("user32.dll")]
private static extern bool GetWindowDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll")]
private static extern int SelectObject(IntPtr hdc, IntPtr hObject);
[DllImport("gdi32.dll")]
private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateBitmap(int width, int height, int bitCount, int bytesPerLine, IntPtr lpBits);
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);
[DllImport("user32.dll")]
private static extern bool ReleaseDC(IntPtr hWnd, IntPtr hdc);
public static void CaptureWindowImage(string className, string windowText, string outputFilePath)
{
// 找到指定窗口的句柄
IntPtr hwnd = FindWindow(className, windowText);
if (hwnd == IntPtr.Zero)
{
Console.WriteLine($"未能找到名为 '{className}' 的窗口");
return;
}
try
{
// 获取窗口的设备上下文
IntPtr hdcWindow = GetWindowDC(hwnd);
// 创建兼容设备上下文
IntPtr hdcScreen = CreateCompatibleDC(hdcWindow);
// 获取屏幕宽度和高度
int width = GetDeviceCaps(hdcScreen, DeviceCap.Width);
int height = GetDeviceCaps(hdcScreen, DeviceCap.Height);
// 创建位图
IntPtr bitmap = CreateBitmap(width, height, PixelFormat.Format32bppArgb, 0, IntPtr.Zero);
// 将位图选择到设备上下文中
SelectObject(hdcScreen, bitmap);
// 偷窥窗口
CopyFromScreen(hwnd, Point.Empty, Point.Zero, new Size(width, height), CopyPixelOperation.SourceCopy);
// 保存位图到文件
using (System.Drawing.Bitmap screenBitmap = new Bitmap(bitmap))
{
screenBitmap.Save(outputFilePath, ImageFormat.Png);
}
// 清理资源
DeleteObject(bitmap);
ReleaseDC(hwnd, hdcWindow);
DeleteDC(hdcScreen);
}
catch (Exception ex)
{
Console.WriteLine($"捕获窗口图像失败: {ex.Message}");
}
}
}
}
// 使用示例
string className = "YourClassName"; // 替换为你需要截取窗口的类名
string windowTitle = "YourWindowTitle"; // 替换为你需要截取窗口的标题
string outputFile = "screenshot.png";
WindowCapture.CaptureWindowImage(className, windowTitle, outputFile);
阅读全文