void CounterThread::run() { int count = 0; while (true) { // 每1秒钟加一并发送信号 msleep(10); HDC hdcScreen = GetDC(NULL); // 获取整个屏幕的设备上下文 HDC hdcMemDC = CreateCompatibleDC(hdcScreen); // 创建内存设备上下文 int width = GetSystemMetrics(SM_CXSCREEN); // 获取屏幕宽度 int height = GetSystemMetrics(SM_CYSCREEN); // 获取屏幕高度 HBITMAP hbmScreen ,hbmOldBitmap ; hbmScreen= CreateCompatibleBitmap(hdcScreen, width, height); // 创建与屏幕设备上下文兼容的位图 hbmOldBitmap= (HBITMAP)SelectObject(hdcMemDC, hbmScreen); // 将位图选入内存设备上下文 BitBlt(hdcMemDC, 0, 0, width, height, hdcScreen, 0, 0, SRCCOPY); // 将屏幕内容绘制到位图上 BITMAP bmpScreen; GetObject(hbmScreen, sizeof(BITMAP), &bmpScreen); // 获取位图信息 BITMAPINFOHEADER bi; bi.biSize = sizeof(BITMAPINFOHEADER); bi.biWidth = bmpScreen.bmWidth; bi.biHeight = bmpScreen.bmHeight; bi.biPlanes = 1; bi.biBitCount = 32; bi.biCompression = BI_RGB; bi.biSizeImage = 0; bi.biXPelsPerMeter = 0; bi.biYPelsPerMeter = 0; bi.biClrUsed = 0; bi.biClrImportant = 0; BYTE pBits = new BYTE[bmpScreen.bmWidth * bmpScreen.bmHeight * 4]; GetDIBits(hdcMemDC, hbmScreen, 0, bmpScreen.bmHeight, pBits, (BITMAPINFO)&bi, DIB_RGB_COLORS); // 将位图数据读取到字节数组中 QImage image(pBits, bmpScreen.bmWidth, bmpScreen.bmHeight, QImage::Format_ARGB32); image = image.convertToFormat(QImage::Format_RGB888).mirrored(false, true); QPixmap pixmap = QPixmap::fromImage(image); // 将字节数组转换为 QPixmap 对象 emit setpix( pixmap); emit countChanged(count); SelectObject(hdcMemDC, hbmOldBitmap); DeleteObject(hbmScreen); DeleteDC(hdcMemDC); ReleaseDC(NULL, hdcScreen); } }这是出错程序,运行一段时间报报错 DWM故障怎么解决该如何改?
时间: 2024-03-16 08:47:14 浏览: 151
根据您提供的代码和错误信息,可能是由于程序每秒钟都会获取屏幕的设备上下文并创建内存设备上下文,导致DWM无法正常工作,建议优化代码,降低程序对系统资源的占用。
您可以尝试在while循环内,增加一些延时操作,例如使用QThread::msleep()方法,让程序每次获取屏幕设备上下文的时间间隔变长,减小程序对系统资源的占用。例如:
```
void CounterThread::run() {
int count = 0;
while (true) {
// 每1秒钟加一并发送信号
msleep(1000);
// 获取屏幕设备上下文等操作
// ...
// 将字节数组转换为 QPixmap 对象
emit setpix(pixmap);
emit countChanged(count);
// 释放资源和延时
SelectObject(hdcMemDC, hbmOldBitmap);
DeleteObject(hbmScreen);
DeleteDC(hdcMemDC);
ReleaseDC(NULL, hdcScreen);
msleep(1000); // 每次循环结束后延时1秒钟
}
}
```
此外,建议您在程序中使用RAII(资源获取即初始化)的思想,避免出现资源泄漏的情况。例如,在获取设备上下文和位图对象之后,需要在使用完毕后及时释放,避免资源占用过多。
阅读全文
相关推荐



















