程序将系统窗口左上角100*100的图像复制到粘贴板上。程序的关键位置上加上了注释,相关知识《windows程序设计》第14章内容
#include <windows.h>
#pragma comment(linker,"/subsystem:\"windows\"" )
HBITMAP GetBitmap(); LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{ static TCHAR szAppName [] = TEXT ("BitBlt") ;
HWND hwnd ;
MSG msg ;
WNDCLASS wndclass ;
wndclass.style = CS_HREDRAW | CS_VREDRAW ;
wndclass.lpfnWndProc = WndProc ;
wndclass.cbClsExtra = ;
wndclass.cbWndExtra = ;
wndclass.hInstance = hInstance ;
wndclass.hIcon = LoadIcon (NULL, IDI_INFORMATION) ;
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ;
wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
wndclass.lpszMenuName = NULL ;
wndclass.lpszClassName = szAppName ; if (!RegisterClass (&wndclass))
{
MessageBox (NULL, TEXT ("This program requires Windows NT!"),
szAppName, MB_ICONERROR) ;
return ;
} hwnd = CreateWindow (szAppName, TEXT ("BitBlt Demo"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL) ;
ShowWindow (hwnd, iCmdShow) ;
UpdateWindow (hwnd) ; while (GetMessage (&msg, NULL, , ))
{
TranslateMessage (&msg) ;
DispatchMessage (&msg) ;
}
return msg.wParam ;
} LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static HDC hdcClient, hdcWindow ;
static HDC hdcMem;
HBITMAP hBitmap;
PAINTSTRUCT ps ; switch (message)
{
case WM_CREATE:
{
hdcClient=GetDC(hwnd); //获得应用程序客户区窗口句柄
hdcWindow = GetWindowDC (NULL) ; //GetWindowDC可以获得整个应用程序窗口句柄(客户区和非客户区)
//当参数传值为NULL的时候,得到系统窗口的句柄
hBitmap=CreateCompatibleBitmap(hdcClient,,); //创建与设备兼容的位图,宽100像素,高100像素
hdcMem=CreateCompatibleDC(hdcClient); //创建内存设备环境句柄
SelectObject(hdcMem,hBitmap); //将位图选进内存设备环境 BitBlt (hdcMem, , , ,, hdcWindow, , , SRCCOPY) ; //将系统窗口左上角100*100的图像像素复制到内存设备环境 OpenClipboard( hwnd ) ; //打开粘贴板
EmptyClipboard() ; //清空粘贴板
SetClipboardData( CF_BITMAP, hBitmap ) ; //设置粘贴板数据,即将位图设置进粘贴 //之前有将新建的位图选进内存设备环境,后来将系统窗口100*100像素图像复制移动到内存
//设备环境。我的理解是,将位图选进内存设备环境之后,针对内存设备环境的操作,改变了
//位图的内容,而不需要再将内存设备环境选进位图了 CloseClipboard() ; //关闭粘贴板
ReleaseDC (hwnd, hdcWindow) ;
return ;
} case WM_SIZE: return ; case WM_PAINT:
hdcClient=BeginPaint (hwnd, &ps) ;
BitBlt (hdcClient, , , ,, hdcMem, , , SRCCOPY) ; //这里我们做一个小测试,将截取的图片显示在客户区
//这样需要将hdcClient和hdcMem定义成static的
EndPaint (hwnd, &ps) ;
return ; case WM_DESTROY:
PostQuitMessage () ;
return ;
} return DefWindowProc (hwnd, message, wParam, lParam) ;
}