问题
Every example codes I saw are GetDC and releaseDC again and again. (or BeginPaint/EndPaint) But I think drawing screen happens very frequently(especially in game), store them in memory is better then get and release all time.
So I did like keep mainDC as global and just use it, only release it when program ends. But why people doesn't do like this? (maybe Get/Release DC costs very little?)
case WM_CREATE:
hdc = GetDC(hWnd); //hdc is declared as global HDC
MyBitmap = LoadBitmap(g_hInst, MAKEINTRESOURCE(IDB_BITMAP1));
return 0;
case WM_PAINT:
MemDC = CreateCompatibleDC(hdc);
OldBitmap = (HBITMAP)SelectObject(MemDC, MyBitmap);
BitBlt(hdc, 0, 0, 300, 300, MemDC, 0, 0, SRCCOPY);
SelectObject(MemDC, OldBitmap);
DeleteDC(MemDC);
return 0;
回答1:
The code you presented here is wrong. First off, you need to read a little more of the documentation. Here is a useful link: Painting and Drawing. Basically there are two ways to update a window:
- In responce to the WM_PAINT message. Use the BeginPaint()/EndPaint() functions to paint the client area properly. This message is sent by the system when a part of the client area is "invalidated" (as a result of resizing, restoring from minimized state, moving a window previously obscuring it, or programmatically invalidating it. WM_PAINT is a low-priority message, received just before the message-queue gets empty.
- Specifically drawing a part or the whole client area without having an invalidated region on it. Use GetDC()/ReleaseDC() for this. Useful if you want to make changes immediately visible, when the application (CPU) is busy.
Writing some code to process the WM_PAINT message is normally almost mandatory, while specifically drawing as well is optional, depending on the requirements of your application.
Never Send or Post a WM_PAINT message yourself, instead invalidate a part or the whole client area - the application will receive a WM_PAINT message before getting idle. If you want the painting to occur immediately call UpdateWindow() - this bypasses the message-queue.
回答2:
A recent (Aug 2016) security update in Windows 10 prevents the reuse of printer device contexts. After printing one document Windows 10 will refuse to print again with that same DC. It has always been a preferred practice to create a new DC for each document, but now it seems to be a requirement in Windows 10.
来源:https://stackoverflow.com/questions/39316141/win32api-why-should-i-getdc-and-releasedc-again-and-again