Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top