I am trying to get a 500x500 screenshot from the 0x0 (top-left) position of screen and put it in a window.
Here is my code (hwnd
is my Window Handle):
HDC appDc = GetDC(hwnd);
HDC dc = GetDC(NULL);
HBITMAP bit开发者_如何学Gomap = CreateCompatibleBitmap(dc, 500, 500);
HDC memoryDc = CreateCompatibleDC(dc);
SelectObject(memoryDc, bitmap);
BitBlt(appDc, 0, 0, 500, 500, dc, 0, 0, SRCCOPY);
ShowWindow(hwnd, SW_SHOW);
SetWindowText(hwnd, _T("Window"));
What am I missing here? I am getting black inside the window instead of the screen capture.
EDIT
It works after I changed memoryDc
to dc
It previously was BitBlt(appDc, 0, 0, 500, 500, memoryDc, 0, 0, SRCCOPY);
But now the problem is SelectObject is not working.I meant Its not putting the Image in HBITMAP. However BitBlt is copying from dc
to appDc
First, there seems to be a confusion with the device contexts. You blit from memoryDc to appDc, but memoryDc does not contain anything - it has been created to be compatible to dc, but that does not mean it shares the content. Also, you do not release the DCs in your example.
Second, your call to ShowWindow() seems to imply that the window has not been visible before. If that is the case, anything that has been "drawn" before has not actually been drawn and will not be visible in the window. Capture the screen content in a bitmap and display it during WM_PAINT.
Since you're calling ShowWindow
for your application's window at the end of the code block, I assume that the window is not visible prior to that time.
If so, then that is your problem because when an invisible window is made visible again, its client area is always repainted. This causes its background to be erased with the default brush for that window (apparently a black brush, in your case), and anything that you painted (using the BitBlt
function) into its device context (DC) to be lost.
A better approach would be to draw the screen capture into a temporary bitmap, instead. Then, just keep a copy of this bitmap around and paint it onto the window whenever you receive a WM_PAINT
message.
精彩评论