Advertisement
jack06215

[OpneCV] capture active window

Jul 7th, 2020
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. #include <Windows.h>
  2. #include <opencv2/videoio.hpp>
  3. #include <opencv2/highgui.hpp>
  4. #include <opencv2/core.hpp>
  5. #include <opencv2/imgproc.hpp>
  6.  
  7. cv::Mat cvCaptureActiveWindow(std::wstring &win_title)
  8. {
  9.     RECT rc;
  10.     std::wstring wide_string = std::wstring(win_title.begin(), win_title.end());
  11.     const wchar_t* result = wide_string.c_str();
  12.     HWND hwnd = FindWindow(NULL, result);
  13.     if (hwnd == NULL)
  14.     {
  15.         std::cout << "it can't find any 'note' window" << std::endl;
  16.         exit(1);
  17.     }
  18.  
  19.     HDC hwindowDC, hwindowCompatibleDC;
  20.  
  21.     int height, width, srcheight, srcwidth;
  22.     HBITMAP hbwindow;
  23.     cv::Mat src;
  24.     BITMAPINFOHEADER  bi;
  25.  
  26.     hwindowDC = GetDC(hwnd);
  27.     hwindowCompatibleDC = CreateCompatibleDC(hwindowDC);
  28.     SetStretchBltMode(hwindowCompatibleDC, COLORONCOLOR);
  29.  
  30.     RECT windowsize;    // get the height and width of the screen
  31.     GetClientRect(hwnd, &windowsize);
  32.  
  33.     srcheight = windowsize.bottom;
  34.     srcwidth = windowsize.right;
  35.     height = windowsize.bottom;  //change this to whatever size you want to resize to
  36.     width = windowsize.right;
  37.  
  38.     std::cout << height << width << std::endl;
  39.  
  40.     src.create(height, width, CV_8UC4);
  41.  
  42.     // create a bitmap
  43.     hbwindow = CreateCompatibleBitmap(hwindowDC, width, height);
  44.     bi.biSize = sizeof(BITMAPINFOHEADER);
  45.     bi.biWidth = width;
  46.     bi.biHeight = -height;  //this is the line that makes it draw upside down or not
  47.     bi.biPlanes = 1;
  48.     bi.biBitCount = 32;
  49.     bi.biCompression = BI_RGB;
  50.     bi.biSizeImage = 0;
  51.     bi.biXPelsPerMeter = 0;
  52.     bi.biYPelsPerMeter = 0;
  53.     bi.biClrUsed = 0;
  54.     bi.biClrImportant = 0;
  55.  
  56.     // use the previously created device context with the bitmap
  57.     SelectObject(hwindowCompatibleDC, hbwindow);
  58.     // copy from the window device context to the bitmap device context
  59.     StretchBlt(hwindowCompatibleDC, 0, 0, width, height, hwindowDC, 0, 0, srcwidth, srcheight, SRCCOPY); //change SRCCOPY to NOTSRCCOPY for wacky colors !
  60.     GetDIBits(hwindowCompatibleDC, hbwindow, 0, height, src.data, (BITMAPINFO*)&bi, DIB_RGB_COLORS);  //copy from hwindowCompatibleDC to hbwindow
  61.  
  62.     // avoid memory leak
  63.     DeleteObject(hbwindow);
  64.     DeleteDC(hwindowCompatibleDC);
  65.     ReleaseDC(hwnd, hwindowDC);
  66.     imwrite("screen.jpg", src);
  67.  
  68.  
  69.     return src;
  70.  
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement