轉自 http://blog.csdn.net/problc/article/details/7063324
截屏程序的源碼網上到處都有,但是基本都不支持多顯示器。
這讓我一度以為支持多顯示器是一件很困難的事情。
(demo http://download.csdn.net/detail/problc/3841959 包含多顯示器支持,窗口高亮,十字放大等)
其實多顯示的截屏跟主顯示器的截屏區別並不大,甚至根本不需要EnumDisplayMonitors之類的調用。只是因為網上有了源碼,我們就懶得想了。
1. DC的問題。
hScrDC = CreateDC( _T("DISPLAY"),NULL,NULL,NULL );//主顯示器DC
hScrDC = ::GetDC(GetDesktopWindow()); //多屏DC
2. 坐標問題。
獲取坐標的時候用VIRTUALSCREEN參數
GetSystemMetrics(SM_CXVIRTUALSCREEN);
GetSystemMetrics(SM_CYVIRTUALSCREEN);
GetSystemMetrics(SM_XVIRTUALSCREEN );
GetSystemMetrics(SM_YVIRTUALSCREEN );
特別注意的是,多顯示器的時候,SM_XVIRTUALSCREEN和SM_YVIRTUALSCREEN是可以為負值的。
所以多顯示器處理時,邊界不要以為是(0,0)->(cx,cy)。
多顯示器的坐標是以主屏幕的左上角為(0,0)。
如果你有單顯示器的源碼,不妨改改上面的幾個小地方,你會發現多屏截屏其實很容易。
int CreateBitmapFromDesktop()
{
RECT Rect;
Rect.top = 20;
Rect.left = 20;
Rect.right = 512;
Rect.bottom = 512;
if (IsRectEmpty(&Rect))
{
return NULL;
}
HDC hSrcDC = NULL, hMemDC = NULL;//屏幕設備描述表句柄 內存設備描述表句柄
HBITMAP hBitmap = NULL, hOldBitmap = NULL; //位圖句柄
int nWidth,nHeight;//位圖寬度和高度
int xScreen,yScreen;//屏幕分辨率
hSrcDC = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL);//主顯示器DC
hMemDC = CreateCompatibleDC(hSrcDC);
xScreen = GetDeviceCaps(hSrcDC,HORZRES);
yScreen = GetDeviceCaps(hSrcDC,VERTRES);
if ( 0 > Rect.left)
{
Rect.left = 0;
}
if ( 0 > Rect.top)
{
Rect.top = 0;
}
if ( Rect.right > xScreen)
{
Rect.right = xScreen;
}
if ( Rect.bottom > yScreen)
{
Rect.bottom = yScreen;
}
nWidth = Rect.right - Rect.left;
nHeight = Rect.bottom - Rect.top;
hBitmap = CreateCompatibleBitmap(hSrcDC, nWidth, nHeight);
//將對象hBitmap選擇到hMemDC中並且替換原來的對象hOldBitmap,返回原來的對象
hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap);
//將桌面DC拷貝到內存DC(設備上下文)
BitBlt(hMemDC, 0, 0, nWidth, nHeight, hSrcDC, Rect.left,Rect.top, SRCCOPY);
//將對象hOldBitmap選擇到內存DC中並替換原來的對象,此時返回原來對象為帶有桌面圖像的位圖對象
//直接理解為將桌面位圖信息存入對象hBitmap中
hBitmap = (HBITMAP)SelectObject(hMemDC, hOldBitmap);
DeleteDC(hSrcDC);
DeleteDC(hMemDC);
BITMAP bmp;
BYTE *pBuffer;
GetObject(hBitmap,sizeof(BITMAP),&bmp);
int image_nchannels = bmp.bmBitsPixel == 1 ? 1 : bmp.bmBitsPixel/8 ;
int image_depth = bmp.bmBitsPixel == 1 ? 1 : 8;
int image_width=bmp.bmWidth;
int image_height=bmp.bmHeight;
pBuffer = new BYTE[image_width*image_height*image_nchannels];
GetBitmapBits(hBitmap,image_height*image_width*image_nchannels,pBuffer);
//pBuffer 內的圖像的像素格式為BGRA 即每個像素是四個指定順序blue green red alpha的組成。
//這是Windows device-independent bitmaps(DIBs)的內存存儲格式。
DeleteObject(hBitmap);
delete [] pBuffer;
return TRUE;
}