Created
April 22, 2023 21:02
-
-
Save criminact/36b68f522f117c051a430c9b1ed8a245 to your computer and use it in GitHub Desktop.
Screen Capture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <Windows.h> | |
| #include <opencv2/opencv.hpp> | |
| using namespace std; | |
| using namespace cv; | |
| Mat captureScreenMat(HWND hwnd) | |
| { | |
| HDC hwindowDC,hwindowCompatibleDC; | |
| int height,width,srcheight,srcwidth; | |
| HBITMAP hbwindow; | |
| Mat src; | |
| BITMAPINFOHEADER bi; | |
| hwindowDC=GetDC(hwnd); | |
| hwindowCompatibleDC=CreateCompatibleDC(hwindowDC); | |
| SetStretchBltMode(hwindowCompatibleDC,COLORONCOLOR); | |
| RECT windowsize; // get the height and width of the screen | |
| GetClientRect(hwnd, &windowsize); | |
| srcheight = windowsize.bottom; | |
| srcwidth = windowsize.right; | |
| height = windowsize.bottom/1; //change this to whatever size you want to resize to | |
| width = windowsize.right/1; | |
| src.create(height,width,CV_8UC4); | |
| // create a bitmap | |
| hbwindow = CreateCompatibleBitmap( hwindowDC, width, height); | |
| bi.biSize = sizeof(BITMAPINFOHEADER); | |
| bi.biWidth = width; | |
| bi.biHeight = -height; //this is the line that makes it draw upside down or not | |
| 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; | |
| // use the previously created device context with the bitmap | |
| SelectObject(hwindowCompatibleDC, hbwindow); | |
| // copy from the window device context to the bitmap device context | |
| StretchBlt( hwindowCompatibleDC, 0,0, width, height, hwindowDC, 0, 0,srcwidth,srcheight, SRCCOPY); //change SRCCOPY to NOTSRCCOPY for wacky colors ! | |
| GetDIBits(hwindowCompatibleDC,hbwindow,0,height,src.data,(BITMAPINFO *)&bi,DIB_RGB_COLORS); //copy from hwindowCompatibleDC to hbwindow | |
| // avoid memory leak | |
| DeleteObject (hbwindow); | |
| DeleteDC(hwindowCompatibleDC); | |
| ReleaseDC(hwnd, hwindowDC); | |
| return src; | |
| } | |
| int main() | |
| { | |
| namedWindow("Screen Capture", CV_WINDOW_NORMAL); | |
| HWND hwnd = GetDesktopWindow(); | |
| int key = 0; | |
| while(key != 27){ | |
| Mat src = captureScreenMat(hwnd); | |
| key = waitKey(30); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment