Programming Windows Chapter 14 BlowUp程序的错误

在Programming Windows Chapter 14 Blow-Up的程序中,在完成屏幕截取后,作者使用如下代码复制屏幕内容到位图:

                HDC hdc = GetDC( _hWnd );
                HDC hdcMem = CreateCompatibleDC( hdc );
                hBitmap = CreateCompatibleBitmap( hdc, abs(ptEnd.x-ptBeg.x), abs(ptEnd.y-ptBeg.y) );
                SelectObject( hdcMem, hBitmap );

                StretchBlt( hdcMem,
                            0, 0,
                            abs(ptEnd.x-ptBeg.x), abs(ptEnd.y-ptBeg.y),
                            hdc,
                            ptBeg.x, ptBeg.y,
                            ptEnd.x-ptBeg.x, ptEnd.y-ptBeg.y,
                            SRCCOPY );

                DeleteDC( hdcMem );
                ReleaseDC( _hWnd, hdc );

在我自己的Win7-32bit下测试是无法正确复制内容的,因为GetDC( _hWnd )只是获取客户区的DC,无法获得客户区外的数据,效果如下:

 复制内容后:

为了正确的复制截取的屏幕内容,我们需要获取屏幕DC,并且使用屏幕坐标来进行操作,代码如下:

                POINT ptScreenBeg = ptBeg;
                POINT ptScreenEnd = ptEnd;
                ClientToScreen( _hWnd, &ptScreenBeg );
                ClientToScreen( _hWnd, &ptScreenEnd );

                HDC hdc = GetDCEx( hWndDesktop, NULL, DCX_CACHE | DCX_LOCKWINDOWUPDATE );
                HDC hdcMem = CreateCompatibleDC( hdc );
                hBitmap = CreateCompatibleBitmap( hdc, abs(ptScreenEnd.x-ptScreenBeg.x), abs(ptScreenEnd.y-ptScreenBeg.y) );
                SelectObject( hdcMem, hBitmap );

                StretchBlt( hdcMem,
                            0, 0,
                            abs(ptScreenEnd.x-ptScreenBeg.x), abs(ptScreenEnd.y-ptScreenBeg.y),
                            hdc,
                            ptScreenBeg.x, ptScreenBeg.y,
                            ptScreenEnd.x-ptScreenBeg.x, ptScreenEnd.y-ptScreenBeg.y,
                            SRCCOPY );

                DeleteDC( hdcMem );
                ReleaseDC( hWndDesktop, hdc );

这样,我们就可以正确将截取的屏幕内容复制到位图了,如下:

 复制内容后: 

原文地址:https://www.cnblogs.com/twjcnblog/p/2328704.html