VC++ 屏幕截图并保存为png格式

谁践踏了优雅 2023-10-04 19:31 133阅读 0赞
  1. #include <windows.h>
  2. #include <gdiplus.h>
  3. //use cstring
  4. #include <atlstr.h>
  5. #pragma comment(lib, "gdiplus.lib")
  6. using namespace Gdiplus;
  7. int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
  8. {
  9. UINT num = 0; // number of image encoders
  10. UINT size = 0; // size of the image encoder array in bytes
  11. ImageCodecInfo* pImageCodecInfo = NULL;
  12. Gdiplus::GetImageEncodersSize(&num, &size);
  13. if (size == 0)
  14. return -1; // Failure
  15. pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
  16. if (pImageCodecInfo == NULL)
  17. return -1; // Failure
  18. Gdiplus::GetImageEncoders(num, size, pImageCodecInfo);
  19. for (UINT j = 0; j < num; ++j)
  20. {
  21. if (wcscmp(pImageCodecInfo[j].MimeType, format) == 0)
  22. {
  23. *pClsid = pImageCodecInfo[j].Clsid;
  24. free(pImageCodecInfo);
  25. return j; // Success
  26. }
  27. }
  28. free(pImageCodecInfo);
  29. return -1; // Failure
  30. }
  31. void CaptureScreen()
  32. {
  33. int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
  34. int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
  35. HWND hDesktopWnd = GetDesktopWindow();
  36. HDC hDesktopDC = GetDC(hDesktopWnd);
  37. HDC hCaptureDC = CreateCompatibleDC(hDesktopDC);
  38. HBITMAP hCaptureBitmap = CreateCompatibleBitmap(hDesktopDC, nScreenWidth, nScreenHeight);
  39. SelectObject(hCaptureDC, hCaptureBitmap);
  40. BitBlt(hCaptureDC, 0, 0, nScreenWidth, nScreenHeight, hDesktopDC, 0, 0, SRCCOPY);
  41. //保存
  42. //初始化GDI
  43. Gdiplus::GdiplusStartupInput gdiplusStartupInput;
  44. ULONG_PTR gdiplusToken;
  45. if (Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL) != Ok)
  46. {
  47. ;
  48. }
  49. SYSTEMTIME Systime;
  50. GetLocalTime(&Systime);
  51. CString szFileName;
  52. szFileName.Format(L"%u-%u-%u-%02u%02u.png",
  53. Systime.wYear, Systime.wMonth, Systime.wDay, Systime.wHour, Systime.wMinute);
  54. CLSID pngClsid;
  55. GetEncoderClsid(L"image/png", &pngClsid);
  56. Gdiplus::Bitmap *pbmSrc = Gdiplus::Bitmap::FromHBITMAP(hCaptureBitmap, NULL);
  57. if (pbmSrc->Save(szFileName, &pngClsid) == Ok) {
  58. ;
  59. }
  60. //卸载GDI
  61. Gdiplus::GdiplusShutdown(gdiplusToken);
  62. DeleteObject(hCaptureBitmap);
  63. ReleaseDC(hDesktopWnd, hDesktopDC);
  64. DeleteDC(hCaptureDC);
  65. }
  66. int main()
  67. {
  68. CaptureScreen();
  69. return 0;
  70. }

发表评论

表情:
评论列表 (有 0 条评论,133人围观)

还没有评论,来说两句吧...

相关阅读