c# 根据句柄截取指定窗口的图片并保存 我要完整代码 我只要一个类
时间: 2024-09-21 16:01:44 浏览: 32
在 C# 中,你可以使用 `System.Drawing` 和 `Windows.Forms` 库来截取指定窗口的图片并保存到本地。以下是一个简单的自包含类 `WindowCapture`,它实现了这个功能:
```csharp
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class WindowCapture : IDisposable
{
private IntPtr hWnd; // 指定的窗口句柄
private bool isDisposed;
public WindowCapture(IntPtr hWndToCapture) {
if (hWndToCapture == IntPtr.Zero)
throw new ArgumentException("Invalid window handle");
this.hWnd = hWndToCapture;
this.isDisposed = false;
}
~WindowCapture() {
Dispose(false);
}
public void CaptureAndSave(string outputFilePath) {
if (isDisposed || hWnd == IntPtr.Zero)
return;
var screenRectangle = GetWindowRect(hWnd);
using (var screenCapture = new Bitmap(screenRectangle.Width, screenRectangle.Height))
{
using (Graphics graphics = Graphics.FromImage(screenCapture))
{
graphics.CopyFromScreen(hWnd, Point.Empty, screenRectangle);
}
screenCapture.Save(outputFilePath, ImageFormat.Png); // 可以替换为其他格式如JPG、BMP等
}
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!isDisposed)
{
if(disposing)
{
// 释放托管资源
}
// 释放非托管资源
hWnd = IntPtr.Zero;
isDisposed = true;
}
}
//
阅读全文