Knowledge Base Nr: 00241 screenshot.cpp - http://www.swe-kaiser.de

Downloads:

Win32: Screenshots mit Programm erstellen

  
//nur ausschnitt des desktops
int Screenshot(HDC hDC, int nStartX, int nStartY, int nSizeX, int nSizeY);

//ganzer desktop oder nur ein komplettes fenster
int Screenshot(HWND hWnd = HWND_DESKTOP);

//////////////////////////////////////
// implementierung

int CImageSupport::Screenshot(HDC hDC, int nStartX, int nStartY, int nSizeX, int nSizeY)
{
if (!hDC || (nStartX < 0) || (nStartY < 0)
|| (nSizeX <= 0) || (nSizeY <= 0))
return IS_NODATA;

if (m_pRGB)
{
GlobalFree(m_pRGB);
m_pRGB = 0;
m_nWidth = m_nHeight = m_nBits = 0;
}

m_pRGB = ISDCToRGB(hDC, nStartX, nStartY, nSizeX, nSizeY);
if (m_pRGB)
{
m_nWidth = nSizeX;
m_nHeight = nSizeY;
m_nBits = 24;
}

return m_pRGB ? IS_OK : IS_LIBERROR;
}

int CImageSupport::Screenshot(HWND hWnd)
{
if (m_pRGB)
{
GlobalFree(m_pRGB);
m_pRGB = 0;
m_nWidth = m_nHeight = m_nBits = 0;
}

HWND hWndDesktop = HWND_DESKTOP;
HDC hDC = ::GetDC(hWndDesktop);

int nStartX, nStartY, nSizeX, nSizeY;

if (hWnd != HWND_DESKTOP)
{
RECT rect;
::GetWindowRect(hWnd, &rect);
nStartX = rect.left;
nStartY = rect.top;
nSizeX = rect.right - rect.left;
nSizeY = rect.bottom - rect.top;
}
else
{
nStartX = 0;
nStartY = 0;
nSizeX = ::GetSystemMetrics(SM_CXSCREEN);
nSizeY = ::GetSystemMetrics(SM_CYSCREEN);
}

int nErr = Screenshot(hDC, nStartX, nStartY, nSizeX, nSizeY);

if (hWndDesktop && hDC)
::ReleaseDC(hWndDesktop, hDC);

return nErr;
}


///////////////////////////////////////////////////
// beispiel

#include "../cpp_classes/ImgSupport.h"

void CCursortestDlg::OnScreenshot()
{
CImageSupport img;

HWND hWnd = GetSafeHwnd();

int nErr = img.Screenshot(hWnd);
ASSERT(!nErr);

nErr = img.SavePNG("c:/temp/screenshot_app.png");
ASSERT(!nErr);
}

void CCursortestDlg::OnScreenshot2()
{
CImageSupport img;

int nErr = img.Screenshot();
ASSERT(!nErr);

nErr = img.SavePNG("c:/temp/screenshot_desktop.png");
ASSERT(!nErr);
}