Jul 062011
 

Currently I’m working on a project that uses screenshots, and I just wanted to share this snippet.

 C++ |  copy code |? 
01
//////////////////////////////////////////////////////////////////////////
02
// Function created by: Lars Werner - http://lars.werner.no
03
//////////////////////////////////////////////////////////////////////////
04
// Inputs:	HWND hParent = the window we want to get DC from, eg
05
//			               ::GetDesktopWindow();
06
//			int x = x-position of the screen
07
//			int y = y-position of the screen
08
//			int nWidth = Width of the screenshot
09
//			int nHeight = Height of the screenshot
10
//
11
//////////////////////////////////////////////////////////////////////////
12
// Return:	HBITMAP = Handle isn't deleted in function, please use
13
//			          DeleteObject() when finished with object!
14
//////////////////////////////////////////////////////////////////////////
15
// Version: 1.0 = Inital Release
16
//////////////////////////////////////////////////////////////////////////
17
HBITMAP ScreenShot(HWND hParent, int x, int y, int nWidth, int nHeight)
18
{
19
	//Get a DC from the parent window
20
	HDC hDC = GetDC(hParent);
21
 
22
	//Create a memory DC to store the picture to
23
	HDC hMemDC = CreateCompatibleDC(hDC);
24
 
25
	//Create the actual picture
26
	HBITMAP hBackground = CreateCompatibleBitmap(hDC, nWidth, nHeight );
27
 
28
	//Select the object and store what we got back
29
	HBITMAP hOld = (HBITMAP)SelectObject(hMemDC, hBackground);
30
 
31
	//Now do the actually painting into the MemDC (result will be in the selected object)
32
	//Note: We ask to return on 0,0,Width,Height and take a blit from x,y
33
	BitBlt(hMemDC, 0, 0, nWidth, nHeight, hDC, x, y, SRCCOPY);
34
 
35
	//Restore the old bitmap (if any)
36
	SelectObject(hMemDC, hOld);
37
 
38
	//Release the DCs we created
39
	ReleaseDC(hParent, hMemDC);
40
	ReleaseDC(hParent, hDC);
41
 
42
	//Return the picture (not a clean method, but you get the drill)
43
	return hBackground;
44
}

Any comments, error or bad design, please let me know in the comments!

 Posted by at 22:16:57

  2 Responses to “Take a screenshot of any given HWND!”

  1. it worked perfectly, thanks!

    The only thing that I’d mention is that the parameter “hParent” should be be the HWND of the actual window you want to get the screenshot as a bitmap

  2. […] Take a screenshot of any given HWND! »  Home  […]

Leave a Reply