Screenshot C++ win32 api
Hi everybody! You have been searching for couple of hours how to make a screenshot in native C++ ? You are only finding weird results which do not work ? Well, you are exactly in the right place!
using namespace std;
void screenshot(POINT a, POINT b)
// copy screen to bitmap
HDC hScreen = GetDC(NULL);
HDC hDC = CreateCompatibleDC(hScreen);
HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, abs(b.x-a.x), abs(b.y-a.y));
HGDIOBJ old_obj = SelectObject(hDC, hBitmap);
BOOL bRet = BitBlt(hDC, 0, 0, abs(b.x-a.x), abs(b.y-a.y), hScreen, a.x, a.y, SRCCOPY);
// save bitmap to clipboard
// clean up
The code above is really clean and simple BUT you cannot just copy past compile the content! It won't work because there is a little detail that EVERYBODY neglect and it thus never work! You have to add a linker. I use CodeBlock for C/C++ programming, so I am going to give you the steps right steps for CodeBlock and then the "general" method.
- For CodeBlock: Right click on your project > Build options... > Linker settings. Then add the following line in Other linker options:
- In general, you just have to add a linker when compiling:
1g++ main.cpp -o test -mwindows
This is it! It should compile without problems!
What the program does ?
The screenshot() function takes two parameters which are two points. The points are respectively the top left corner and the bottom right corner of the shape formed by the screen area you want to capture.
It means you can take also partial screenshots, it's up to you! For the syntax of the POINT object, you have a basic example in the main() function.
Once called, the screenshot function will capture the screen and then copy the image in your clipboard: if you Ctrl+V in paint, the capture will magically appear!
This is it! This article wasn't really a tutorial, but a resource (which in my opinion misses on the net). See you!