<p>Why does the following code sometimes causes an Exception with the contents "CLIPBRD_E_CANT_OPEN":</p>

<pre><code>Clipboard.SetText(str);
</code></pre>

<p>This usually occurs the first time the Clipboard is used in the application and not after that.</p>

[{'answer_id': 68857, 'author': 'Tadmas', 'author_id': 3750, 'author_profile': 'https://Stackoverflow.com/users/3750', 'pm_score': 6, 'selected': True, 'text': '<p>Actually, I think this is the <a href="https://cloudblogs.microsoft.com/enterprisemobility/2006/11/20/why-does-my-shared-clipboard-not-work-part-2/" rel="noreferrer">fault of the Win32 API</a>.</p>\n\n<p>To set data in the clipboard, you have to <a href="http://msdn.microsoft.com/en-us/library/ms649048(VS.85).aspx" rel="noreferrer">open it</a> first.  Only one process can have the clipboard open at a time.  So, when you check, if another process has the clipboard open <em>for any reason</em>, your attempt to open it will fail.</p>\n\n<p>It just so happens that Terminal Services keeps track of the clipboard, and on older versions of Windows (pre-Vista), you have to open the clipboard to see what\'s inside... which ends up blocking you.  The only solution is to wait until Terminal Services closes the clipboard and try again.</p>\n\n<p>It\'s important to realize that this is not specific to Terminal Services, though: it can happen with anything.  Working with the clipboard in Win32 is a giant race condition.  But, since by design you\'re only supposed to muck around with the clipboard in response to user input, this usually doesn\'t present a problem.</p>\n'}, {'answer_id': 69081, 'author': 'Robert Wagner', 'author_id': 10784, 'author_profile': 'https://Stackoverflow.com/users/10784', 'pm_score': 6, 'selected': False, 'text': '<p>This is caused by a bug/feature in Terminal Services clipboard (and possible other things) and the .NET implementation of the clipboard. A delay in opening the clipboard causes the error, which usually passes within a few milliseconds.</p>\n\n<p>The solution is to try multiple times within a loop and sleep in between.</p>\n\n<pre><code>for (int i = 0; i &lt; 10; i++)\n{\n    try\n    {\n        Clipboard.SetText(str);\n        return;\n    }\n    catch { }\n    System.Threading.Thread.Sleep(10);\n} \n</code></pre>\n'}, {'answer_id': 11726104, 'author': 'Yishai Galatzer', 'author_id': 1048066, 'author_profile': 'https://Stackoverflow.com/users/1048066', 'pm_score': 3, 'selected': False, 'text': "<p>Actually there could be another issue at hand. The framework call (both the WPF and winform flavors) to something like this (code is from reflector):</p>\n\n<pre><code>private static void SetDataInternal(string format, object data)\n{\n    bool flag;\n    if (IsDataFormatAutoConvert(format))\n    {\n        flag = true;\n    }\n    else\n    {\n        flag = false;\n    }\n    IDataObject obj2 = new DataObject();\n    obj2.SetData(format, data, flag);\n    SetDataObject(obj2, true);\n}\n</code></pre>\n\n<p>Note that SetDataObject is always called with true in this case.</p>\n\n<p>Internally that triggers two calls to the win32 api, one to set the data and one to flush it from your app so it's available after the app closes.</p>\n\n<p>I've seen several apps (some chrome plugin, and a download manager) that listen to the clipboard event. As soon as the first call hits, the app will open the clipboard to look into the data, and the second call to flush will fail.</p>\n\n<p>Haven't found a good solution except to write my own clipboard class that uses direct win32 API or to call setDataObject directly with false for keeping data after the app closes.</p>\n"}, {'answer_id': 30165665, 'author': 'Mar', 'author_id': 44217, 'author_profile': 'https://Stackoverflow.com/users/44217', 'pm_score': 4, 'selected': False, 'text': '<p>I solved this issue for my own app using native Win32 functions: OpenClipboard(), CloseClipboard() and SetClipboardData().</p>\n\n<p>Below the wrapper class I made. Could anyone <strong>please</strong> review it and <strong>tell if it is correct or not</strong>. Especially when the managed code is running as x64 app (I use Any CPU in the project options). <strong>What happens when I link to x86 libraries from x64 app?</strong></p>\n\n<p>Thank you!</p>\n\n<p>Here\'s the code:</p>\n\n<pre><code>public static class ClipboardNative\n{\n    [DllImport("user32.dll")]\n    private static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n    [DllImport("user32.dll")]\n    private static extern bool CloseClipboard();\n\n    [DllImport("user32.dll")]\n    private static extern bool SetClipboardData(uint uFormat, IntPtr data);\n\n    private const uint CF_UNICODETEXT = 13;\n\n    public static bool CopyTextToClipboard(string text)\n    {\n        if (!OpenClipboard(IntPtr.Zero)){\n            return false;\n        }\n\n        var global = Marshal.StringToHGlobalUni(text);\n\n        SetClipboardData(CF_UNICODETEXT, global);\n        CloseClipboard();\n\n        //-------------------------------------------\n        // Not sure, but it looks like we do not need \n        // to free HGLOBAL because Clipboard is now \n        // responsible for the copied data. (?)\n        //\n        // Otherwise the second call will crash\n        // the app with a Win32 exception \n        // inside OpenClipboard() function\n        //-------------------------------------------\n        // Marshal.FreeHGlobal(global);\n\n        return true;\n    }\n}\n</code></pre>\n'}, {'answer_id': 39125098, 'author': 'pr0gg3r', 'author_id': 1159244, 'author_profile': 'https://Stackoverflow.com/users/1159244', 'pm_score': 5, 'selected': False, 'text': '<p>I know this question is old, but the problem still exists. As mentioned before, this exception occurs when the system clipboard is blocked by another process. Unfortunately, there are many snipping tools, programs for screenshots and file copy tools which can block the Windows clipboard. So you will get the exception every time you try to use <code>Clipboard.SetText(str)</code> when such a tool is installed on your PC.</p>\n<p>Solution:</p>\n<p>never use</p>\n<pre><code>Clipboard.SetText(str);\n</code></pre>\n<p>use instead</p>\n<pre><code>Clipboard.SetDataObject(str);\n</code></pre>\n'}, {'answer_id': 43910453, 'author': 'Ellix4u', 'author_id': 3690683, 'author_profile': 'https://Stackoverflow.com/users/3690683', 'pm_score': 1, 'selected': False, 'text': '<p>This happen to me in my WPF application. I got OpenClipboard Failed (Exception from HRESULT: 0x800401D0 (CLIPBRD_E_CANT_OPEN)).</p>\n\n<p>i use</p>\n\n<pre><code>ApplicationCommands.Copy.Execute(null, myDataGrid);\n</code></pre>\n\n<p>solution is to clear the clipboard first</p>\n\n<pre><code>Clipboard.Clear();\nApplicationCommands.Copy.Execute(null, myDataGrid);\n</code></pre>\n'}, {'answer_id': 64685710, 'author': 'Bret Pehrson', 'author_id': 7547283, 'author_profile': 'https://Stackoverflow.com/users/7547283', 'pm_score': 2, 'selected': False, 'text': '<p>Use the WinForms version (yes, there is no harm using WinForms in WPF applications), it handles everything you need:</p>\n<pre><code>System.Windows.Forms.Clipboard.SetDataObject(yourText, true, 10, 100);\n</code></pre>\n<p>This will attempt to copy yourText to the clipboard, it remains after your app exists, will attempt up to 10 times, and will wait 100ms between each attempt.</p>\n<p>Ref. <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.clipboard.setdataobject?view=netframework-4.7.2#System_Windows_Forms_Clipboard_SetDataObject_System_Object_System_Boolean_System_Int32_System_Int32" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.clipboard.setdataobject?view=netframework-4.7.2#System_Windows_Forms_Clipboard_SetDataObject_System_Object_System_Boolean_System_Int32_System_Int32</a>_</p>\n'}, {'answer_id': 74564870, 'author': 'Marek J', 'author_id': 6423994, 'author_profile': 'https://Stackoverflow.com/users/6423994', 'pm_score': 0, 'selected': False, 'text': '<p>The difference between Cliboard.SetText and Cliboard.SetDataObject in WPF is that the text is not copied to the clipboard, only the pointer. I checked the source code. If we call SetDataObject(data, true) Clipoard.Flush() will also be called. Thanks to this, text or data is available even after closing the application. I think Windows applications only call Flush() when they are shutting down. Thanks to this, it saves memory and at the same time gives access to data without an active application.</p>\n<p>Copy to clipboard:</p>\n<pre><code>IDataObject CopyStringToClipboard(string s)\n{\n  var dataObject = new DataObject(s);\n  Clipboard.SetDataObject(dataObject, false);\n  return dataObject;\n}\n</code></pre>\n<p>Code when app or window is closed:</p>\n<pre><code>try\n{\n  if ((clipboardData != null) &amp;&amp; Clipboard.IsCurrent(clipboardData))\n    Clipboard.Flush();\n}\ncatch (COMException ex) {}\n</code></pre>\n<p>clipboardData is a window class field or static variable.</p>\n'}, {'answer_id': 74679767, 'author': 'sarh', 'author_id': 282694, 'author_profile': 'https://Stackoverflow.com/users/282694', 'pm_score': 0, 'selected': False, 'text': "<p>That's not a solution, just some additional information on how to reproduce it when all solutions work on your PC and fail somewhere else. As mentioned in the accepted answer - clipboard can be busy by some other app. You just need to handle this failure properly, to explain user somehow why it does not work.</p>\n<p>So, just create a new console app with few lines below and run it. And while it is running - test your primary app on how it is handles busy clipboard:</p>\n<pre><code>class Program\n{\n    [DllImport(&quot;user32.dll&quot;)]\n    private static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n    [DllImport(&quot;user32.dll&quot;)]\n    private static extern bool CloseClipboard();\n\n    static void Main(string[] args)\n    {\n        bool res = OpenClipboard(IntPtr.Zero);\n        Console.Write(res);\n        Console.Read();\n        CloseClipboard();\n    }\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/68666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10784/']