winapiclipboardclipboard-interaction

In what circumstances will GetClipboardData(CF_TEXT) return NULL?


I have this intermittent and incosistent problem which has been driving me crazy for a long time: In a program of mine, GetClipboardData(CF_TEXT) succeeds 90% (or so) of the time, but every once in a while it returns NULL.

This is despite the fact that OpenClipboard() always succeeds (and return value checked) before calling GetClipboardData(CF_TEXT).

Please note that the 90% success ratio is for the same exact page! (i.e. I know there is a CF_TEXT content there)

Note: When it fails, I immediately call GetLastError() but all it returns is: "The operation completed successfully".

The code in question is as simple as:

if (::OpenClipboard(hwndW))
{
  HANDLE handleClip = ::GetClipboardData(CF_TEXT);
  if (handleClip == NULL)
    dw = GetLastError()
}

What could possibly inject the wrong GetLastError() code into this?

Any idea what could prompt such inconsistent behavior?

Is it possible that some other process is locking the clipboard? If so, how do I take it back?

How do I troubleshoot or debug something like this?


Solution

  • I did a Google search and found someone else with a similar problem (scroll down to find the particular response) that turned out to be due to re-entrancy. Do you call EmptyClipboard() anywhere and then react to changes? Perhaps you have a re-entrancy problem.

    Update after code snippet provided
    In the code you posted, the condition is wrong before calling GetLastError. You're only calling it when you get a non-NULL result, rather than when you get a NULL result. If you fix that, you should get a better answer from GetLastError. This MSDN article should help in deciphering what the result of GetLastError actually means.

    Update after corrected code snippet
    My guess is that you're facing a race condition with some other application accessing the clipboard. I would recommend checking to see if you have any other tools running that might do this.