百度到的代码今天发现有个bug,代码链接为C# 根据窗口句柄获取窗口截图,代码如下
public class WindowCaptureHelper
{
[DllImport("user32.dll")]
private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rectangle rect);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);
[DllImport("gdi32.dll")]
private static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
[DllImport("gdi32.dll")]
private static extern int DeleteDC(IntPtr hdc);
[DllImport("user32.dll")]
private static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, int nFlags);
[DllImport("user32.dll")]
private static extern IntPtr GetWindowDC(IntPtr hwnd);
public static Bitmap GetShotCutImage(IntPtr hWnd)
{
var hscrdc = GetWindowDC(hWnd);
var windowRect = new Rectangle();
GetWindowRect(hWnd, ref windowRect);
int width = Math.Abs(windowRect.Width- windowRect.X);
int height = Math.Abs(windowRect.Height- windowRect.Y);
var hbitmap = CreateCompatibleBitmap(hscrdc, width, height);
var hmemdc = CreateCompatibleDC(hscrdc);
SelectObject(hmemdc, hbitmap);
PrintWindow(hWnd, hmemdc, 0);
var bmp = Image.FromHbitmap(hbitmap);
DeleteDC(hscrdc);
DeleteDC(hmemdc);
return bmp;
}
}
客户说一天后就崩了,看了一下任务管理器,程序运行内存没有变化.但是过了一个小时,任务管理器总内存涨了10%,大概800M,这应该就是使用dll未释放指针了.使用ChatGPT,把代码输入进去,直接为我找到了问题.
![](https://i-blog.csdnimg.cn/blog_migrate/f89160d2674962d1ab5ee8b292ea0c51.png)
[DllImport("user32.dll")]
public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
public static Bitmap GetShotCutImage(IntPtr hWnd)
{
var hscrdc = GetWindowDC(hWnd);
var windowRect = new Rectangle();
GetWindowRect(hWnd, ref windowRect);
int width = Math.Abs(windowRect.Width - windowRect.X);
int height = Math.Abs(windowRect.Height - windowRect.Y);
var hbitmap = CreateCompatibleBitmap(hscrdc, width, height);
var hmemdc = CreateCompatibleDC(hscrdc);
SelectObject(hmemdc, hbitmap);
PrintWindow(hWnd, hmemdc, 0);
var bmp = Image.FromHbitmap(hbitmap);
DeleteObject(hbitmap);
ReleaseDC(hWnd, hscrdc);
//DeleteDC(hscrdc); //原代码,造成了内存未释放
DeleteDC(hmemdc);
return bmp;
}
测试了20分钟,内存没有上升了