How can I fix "Cannot open clipboard: Access Denied" errors?

norgepaul picture norgepaul · Dec 7, 2009 · Viewed 30.6k times · Source

I am using the following code to copy text to the clipboard:

  Clipboard.Open;
  try
    Clipboard.AsText := GenerateClipboardText;
  finally
    Clipboard.Close;
  end;

Seemingly at random I get "Cannot open clipboard: Access Denied" errors. I'm guessing that these errors are caused by other application locking the clipboard, but I never seem to be doing anything with other applications that should cause the locks.

Strangely my users seem to be reporting more of the errors with Vista and Windows 7 than with XP.

Is there a way to check if the clipboard is locked before trying to access it?

Answer

Daniel Rikowski picture Daniel Rikowski · Dec 7, 2009

This is not a Delphi problem. Because the clipboard can be locked any moment, even if you check, if the clipboard is currently not locked, it might become locked directly after the check.

You have two possibilities here:

  1. Don't use the Delphi clipboard class. Instead use raw API functions, where you have a little more fine-grained control over possible error situations.
  2. Expect your code to fail by adding an exception handler. Then add some retry code, i.e. retry to set the text three times, perhaps with exponential backoff, before throwing your own error.

I'd recommend the second solution, because it'd be the more Delphi-like approach and in the end will result in cleaner code.

while not Success do
try
  //Set the clipboard
  Success := True;
except
  on Exception do
  begin
    Inc(RetryCount);
    if RetryCount < 3 then 
      Sleep(RetryCount * 100)
    else 
      raise MyException.Create('Cannot set clipboard');
  end;
end;