0

Ultimately I want to save the Image from the clipboard to an img file(.bmp, JPEG whatever). That's a long road, so I just want to load the image into the window but I don't seem to have any succes with GetClipboardData(). It always returns NULL. Searching has not helped me.. Code to get the HBITMAP from the clipboard:

HWND hwnd = FindWindow("ConsoleWindowClass", NULL);
if(!OpenClipboard(hwnd)) printf("Error opening clipboard\n");
HBITMAP hbmp;
EmptyClipboard();
Sleep(3000);
if((hbmp = (HBITMAP)GetClipboardData(CF_BITMAP)) == NULL) printf("Error geting clipboard data\n");

Output: Error getting clipboard data

I tried using GetLastError() with formatting and everything, and it says file not found. The sleep is to wait for me to press print screen, to be sure the clipboard has some data.

kundrata
  • 651
  • 3
  • 12
  • 24

2 Answers2

1

See the comments here:

If an application calls OpenClipboard with hwnd set to NULL, EmptyClipboard sets the clipboard owner to NULL; this causes SetClipboardData to fail.

Have you verified that FindWindow isn't returning null? If it does, OpenClipboard will still succeed but GetClipboardData will fail. My bet is this is exactly what's happening.

Carey Gregory
  • 6,836
  • 2
  • 26
  • 47
  • Tried it now, hwnd is not NULL, that doesn't seem to be the problem. – kundrata Mar 23 '13 at 19:54
  • I also added CloseClipboard at the beginning of the code, in case anything has the clipboard open. The result is the same – kundrata Mar 23 '13 at 19:56
  • Then I would expect the problem is you're asking for bitmap data but using a console window handle. Console windows don't recognize bitmap data, only text. Instead of print screen, I would place some text on the clipboard using notepad to test that. – Carey Gregory Mar 23 '13 at 20:13
  • Using CF_TEXT worked. This time I created a window, placed the code to get hbitmap from the clipboard in the window procedure, when WM_CREATE is called. GetClipboardData returns NULL just as before. Nice observation though. – kundrata Mar 23 '13 at 20:50
  • Glad to help find a solution. :-) – Carey Gregory Mar 23 '13 at 22:57
1

The problem has to do with Sleep() and EmptyClipboard()
GetClipboardData() fails because the clipboard is empty. The exact error is: "Thread does not have a clipboard open".
When using CF_TEXT this does not happen, I think because the string can be filled with a null, but a HBITMAP cannot get something other than a handle for a bitmap content.
I used to Sleep(3000) in order to have time to press print screen, but the snapshot is not saved in the clipboard since I have it open in my application. Removing EmptyClipboard() solves the problem, thus getting the snapshot already present in the clipboard before opening it programmaticaly.

kundrata
  • 651
  • 3
  • 12
  • 24