设备上下文 -- From GameTutorials, LLC

    设备上下文(Device Context),MSDN中的定义是:“A device context is a structure that defines a set of graphic

objects and their associated attributes, as well as the graphic modes that affect output. ”我们也称之为HDC(handle to

a device context),共有4种HDC:
    1、 Display
    2、 Printer
    3、 Memory
    4、 Information
    最常用的两个是Display和Memory。分别支持在显示器和位图上的绘图操作。示例代码获得一个窗口的HDC,然后填充窗口为黑色

 

#include #define WIN_WIDTH 320 #define WIN_HEIGHT 240 #define class_name TEXT("GameTutorials_HDC") LRESULT CALLBACK WinProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hprev, PSTR cmdline, int ishow) { HWND hwnd; MSG msg; WNDCLASSEX wndclassex = {0}; // EX后缀意思是“extended style” wndclassex.cbSize = sizeof(WNDCLASSEX); wndclassex.style = CS_HREDRAW | CS_VREDRAW; wndclassex.lpfnWndProc = WinProc;// 指点窗口的窗口过程处理函数 wndclassex.hInstance = hinstance; wndclassex.lpszClassName = class_name; wndclassex.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclassex.hCursor = (HCURSOR)LoadImage(NULL, MAKEINTRESOURCE(IDC_ARROW), IMAGE_CURSOR, 0, 0, LR_SHARED); RegisterClassEx(&wndclassex); hwnd = CreateWindowEx(NULL, class_name, TEXT("www.GameTutorials.com -- HDC's"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, WIN_WIDTH, WIN_HEIGHT, NULL, NULL, hinstance, NULL); if(!hwnd) return EXIT_FAILURE; HDC hdc = GetDC(hwnd); // 获取窗口的HDC if(!hdc) // hdc 为 NULL 表示获取窗口的HDC失败 return EXIT_FAILURE; ShowWindow(hwnd, ishow); UpdateWindow(hwnd); RECT rect; // 矩形数据结构 GetClientRect(hwnd,&rect); // 将客户端窗口的坐标填充到rect中 FillRect(hdc,&rect,(HBRUSH)GetStockObject(BLACK_BRUSH)); while(1) { if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // 区分一下PeekMessage和GetMessage // Peek是有“偷窥”的意思,因此PeekMessage并不一定会从消息队列中删除消息(可以设置) // 而GetMessage则会一直等待队列中的消息,并会将取出的消息从消息队列中删除 { if(msg.message == WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } else { } } ReleaseDC(hwnd,hdc); // 申请后必须要记得释放掉 // 注销窗口类 // 注意如果采用RegisterClass注册的窗口类,则不需要调用UnregisterClass注销 UnregisterClass(class_name,hinstance); return msg.wParam; } LRESULT CALLBACK WinProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) // 一个简单见的窗口过程 { switch(message) { case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, message, wparam, lparam); }

你可能感兴趣的:(设备上下文 -- From GameTutorials, LLC)