How to get screenshot of a window as bitmap object in C++? Supposed that I already have the window handle. And I want to know also whether it's possible to get the screenshot of a window when it's in minimized state?
C++ here means VC++ with all the libraries associated with Windows XP+ (win32).
Press Ctrl + PrtScn keys. The entire screen changes to gray including the open menu. Select Mode, or in earlier versions of Windows, select the arrow next to the New button. Select the kind of snip you want, and then select the area of the screen capture that you want to capture.
Press the Windows key + PrintScreen on your keyboard (or, PrtSc). Screenshots are automatically saved to Pictures/Screenshots in your user directory (C:/Users/%username%/Pictures/Screenshots by default).
When what you want to capture is displayed on the screen, press the Print Screen key. Open your favorite image editor (like Paint, GIMP, Photoshop, GIMPshop, Paintshop Pro, Irfanview, and others). Create a new image, and press CTRL + V to paste the screenshot. Save your image as a JPG, GIF, or PNG file.
you should call the PrintWindow API:
void CScreenShotDlg::OnPaint()
{
// device context for painting
CPaintDC dc(this);
// Get the window handle of calculator application.
HWND hWnd = ::FindWindow( 0, _T( "Calculator" ));
// Take screenshot.
PrintWindow( hWnd,
dc.GetSafeHdc(),
0 );
}
see this question: getting window screenshot windows API
if you are not using MFC, here the pure PrintWindow signature:
BOOL PrintWindow(
HWND hwnd,
HDC hdcBlt,
UINT nFlags
);
see MSDN for more details: http://msdn.microsoft.com/en-us/library/dd162869(v=vs.85).aspx
about how to save it as bitmap asMatteo said depends on the actual framework you are using...
EDIT:
here full example in raw C++
#define _WIN32_WINNT 0x0501 //xp
#include <windows.h>
int main()
{
RECT rc;
HWND hwnd = FindWindow(TEXT("Notepad"), NULL); //the window can't be min
if (hwnd == NULL)
{
cout << "it can't find any 'note' window" << endl;
return 0;
}
GetClientRect(hwnd, &rc);
//create
HDC hdcScreen = GetDC(NULL);
HDC hdc = CreateCompatibleDC(hdcScreen);
HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen,
rc.right - rc.left, rc.bottom - rc.top);
SelectObject(hdc, hbmp);
//Print to memory hdc
PrintWindow(hwnd, hdc, PW_CLIENTONLY);
//copy to clipboard
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(CF_BITMAP, hbmp);
CloseClipboard();
//release
DeleteDC(hdc);
DeleteObject(hbmp);
ReleaseDC(NULL, hdcScreen);
cout << "success copy to clipboard, please paste it to the 'mspaint'" << endl;
return 0;
}
If anybody is interested in getting PrintWindow picture of minimized window, here you can get the idea, how to get the thing done: http://www.codeproject.com/Articles/20651/Capturing-Minimized-Window-A-Kid-s-Trick
Happy coding;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With