1

Possible Duplicate:
How can I fix “Cannot open clipboard: Access Denied” errors?

Hi.

From time to time I get a "Cannot open clipboard" error when I try to do something like this:

procedure TForm1.btnCopyClick(Sender: TObject);
begin
  Clipbrd.Clipboard.AsText:= Memo.Text;
end;

Any ideas why I get this error?

EDIT:

I have found this possible solution:

procedure StrToClipbrd(StrValue: string);
VAR hMem: THandle;
    pMem: PChar;
begin
 hMem := GlobalAlloc(GHND or GMEM_SHARE, Length(StrValue) + 1);
 if hMem <> 0 then
  begin
   pMem := GlobalLock(hMem);
   if pMem <> nil then
    begin
     StrPCopy(pMem, StrValue);
     GlobalUnlock(hMem);
     if OpenClipboard(0) then
      begin
       EmptyClipboard;
       SetClipboardData(CF_TEXT, hMem);
       CloseClipboard;
      end
     else GlobalFree(hMem);
    end
   else GlobalFree(hMem);
  end;
end;

Delphi 7, Win xp

Community
  • 1
  • 1
Gabriel
  • 20,797
  • 27
  • 159
  • 293
  • Are there reasons other than "Access denied" why this operation can fail? In this case it's not necessarily a duplicate – jpfollenius Jan 10 '11 at 15:32
  • 2
    Did you try calling GetLastError() WinAPI function to find out the error code? – Eugene Mayevski 'Callback Jan 10 '11 at 15:35
  • Hi guys, I clicked delete for my answer. What to do next is probably upon you - I'm newbie here :) and +1 for the comment above –  Jan 10 '11 at 15:49
  • @Smasher No, it always fails because it's locked by another thread – David Heffernan Jan 10 '11 at 15:57
  • I get only a "Cannot open clipboard" msg without "Access Denied" after it. Though, the proposed solution (by Andreas) seems to be what I am looking for. I will have to test it. – Gabriel Jan 10 '11 at 16:10
  • The answer states "Because the clipboard can be locked any moment...". Does it mean that the error appears only when you write to clipboard? Or it needs to be locked also when you read from it? – Gabriel Jan 10 '11 at 16:16
  • 1
    Your edited code circumvents the error message from your original code: when `if OpenClipboard(0)` returns false, you effectively have the `exception` cause. – Jeroen Wiert Pluimers Jan 10 '11 at 16:58
  • +1 @Jeroen Pluimers - sounds like a solution, but to be more specific, you should use OpenClipboard and EmptyClipboard subsequently. After this, you would own the clipboard, so you can put the data there and finally release the clipboard using CloseClipboard. –  Jan 10 '11 at 17:49
  • 1
    @Altar I think @Jeroen is saying that this will get rid of the exception, but will still fail to put the data on the clipboard if it's opened by another thread. – David Heffernan Jan 10 '11 at 19:46
  • @David, @Altar: this indeed was what I was saying. The exception indicates the failure. @Altar: your new solution will not copy in case `if OpenClipboard(0) then` fails. – Jeroen Wiert Pluimers Jan 10 '11 at 21:37

0 Answers0