Jul 062011

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

// Function created by: Lars Werner - http://lars.werner.no
// Inputs: HWND hParent = the window we want to get DC from, eg
// ::GetDesktopWindow();
// int x = x-position of the screen
// int y = y-position of the screen
// int nWidth = Width of the screenshot
// int nHeight = Height of the screenshot
// Return: HBITMAP = Handle isn't deleted in function, please use
// DeleteObject() when finished with object!
// Version: 1.0 = Inital Release
HBITMAP ScreenShot(HWND hParent, int x, int y, int nWidth, int nHeight)
//Get a DC from the parent window
HDC hDC = GetDC(hParent);

//Create a memory DC to store the picture to
HDC hMemDC = CreateCompatibleDC(hDC);

//Create the actual picture
HBITMAP hBackground = CreateCompatibleBitmap(hDC, nWidth, nHeight );

//Select the object and store what we got back
HBITMAP hOld = (HBITMAP)SelectObject(hMemDC, hBackground);

//Now do the actually painting into the MemDC (result will be in the selected object)
//Note: We ask to return on 0,0,Width,Height and take a blit from x,y
BitBlt(hMemDC, 0, 0, nWidth, nHeight, hDC, x, y, SRCCOPY);

//Restore the old bitmap (if any)
SelectObject(hMemDC, hOld);

//Release the DCs we created
ReleaseDC(hParent, hMemDC);
ReleaseDC(hParent, hDC);

//Return the picture (not a clean method, but you get the drill)
return hBackground;

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

%d bloggers like this: