I'm currently trying to capture a window from my application to a bitmap. I want to do this if the Window is completely visible, or partly/completely obscured. I found some Win API code at using the WM_PRINT message that seemed to be just what I wanted. I am new to Win API, but managed to convert it for Delphi (see below), using the clipboard as a test item only. The routine captures the screen exactly as I want. HOWEVER I get an ERangeError Range Check Error at the SendMessage line on about 2 out of 3 occasions. I've tried all sorts to determine what leads to exceptions or success, but as far as I can tell the failures seem random. The only thing that has worked is removing the range check from the Project options, but this doesn't seem to be a very satisfactory answer.
Has anybody got any idea what's happening and how to solve it? Being new to Win API I'm not sure what bits should be protected by try...finally and/or try...exception blocks. All suggestions gratefully received.
procedure TForm1.CaptureWindow;
var
hBmp: HBITMAP;
hDCForm: HDC;
hDCMem: HDC;
hOld: HGDIOBJ;
hWndForm: HWND;
begin
hDCForm := GetDeviceContext(hWndForm);
hDCMem := CreateCompatibleDC(0);
hBmp := CreateCompatibleBitmap(hDCForm, ClientWidth, ClientHeight);
ReleaseDC(hWndForm, hDCForm);
hOld := SelectObject(hDCMem, hBmp);
SendMessage(hWndForm, WM_PRINT, hDCMem, PRF_CLIENT);
SelectObject(hDCMem, hOld);
DeleteObject(hDCMem);
OpenClipboard(hWndForm);
EmptyClipboard();
SetClipboardData(CF_BITMAP, hBmp);
CloseClipboard();
DeleteObject(hBmp);
end;
Has anybody got any idea what's happening and how to solve it? Being new to Win API I'm not sure what bits should be protected by try...finally and/or try...exception blocks. All suggestions gratefully received.
procedure TForm1.CaptureWindow;
var
hBmp: HBITMAP;
hDCForm: HDC;
hDCMem: HDC;
hOld: HGDIOBJ;
hWndForm: HWND;
begin
hDCForm := GetDeviceContext(hWndForm);
hDCMem := CreateCompatibleDC(0);
hBmp := CreateCompatibleBitmap(hDCForm, ClientWidth, ClientHeight);
ReleaseDC(hWndForm, hDCForm);
hOld := SelectObject(hDCMem, hBmp);
SendMessage(hWndForm, WM_PRINT, hDCMem, PRF_CLIENT);
SelectObject(hDCMem, hOld);
DeleteObject(hDCMem);
OpenClipboard(hWndForm);
EmptyClipboard();
SetClipboardData(CF_BITMAP, hBmp);
CloseClipboard();
DeleteObject(hBmp);
end;