Search code examples
delphidelphi-2010clipboardcopy-paste

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


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?


Solution

  • 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.

    var
      Success : boolean;
      RetryCount : integer;
    begin
      RetryCount := 0;
      Success := false;
      while not Success do
        try
          //
          // Set the clipboard here
          //
          Success := True;
        except
          on E: EClipboardException do
          begin
            Inc(RetryCount);
            if RetryCount < 3 then
              Sleep(RetryCount * 100)
            else
              raise Exception.Create('Cannot set clipboard after three attempts');
          end else
            raise;  // if not a clipboard problem then re-raise 
        end;
    end;