CLIPBRD_E_CANT_OPEN error when setting the Clipboard from .NET

前端 未结 7 1172
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 08:08

Why does the following code sometimes causes an Exception with the contents \"CLIPBRD_E_CANT_OPEN\":

Clipboard.SetText(str);

This usually o

相关标签:
7条回答
  • 2020-11-29 08:44

    I solved this issue for my own app using native Win32 functions: OpenClipboard(), CloseClipboard() and SetClipboardData().

    Below the wrapper class I made. Could anyone please review it and tell if it is correct or not. Especially when the managed code is running as x64 app (I use Any CPU in the project options). What happens when I link to x86 libraries from x64 app?

    Thank you!

    Here's the code:

    public static class ClipboardNative
    {
        [DllImport("user32.dll")]
        private static extern bool OpenClipboard(IntPtr hWndNewOwner);
    
        [DllImport("user32.dll")]
        private static extern bool CloseClipboard();
    
        [DllImport("user32.dll")]
        private static extern bool SetClipboardData(uint uFormat, IntPtr data);
    
        private const uint CF_UNICODETEXT = 13;
    
        public static bool CopyTextToClipboard(string text)
        {
            if (!OpenClipboard(IntPtr.Zero)){
                return false;
            }
    
            var global = Marshal.StringToHGlobalUni(text);
    
            SetClipboardData(CF_UNICODETEXT, global);
            CloseClipboard();
    
            //-------------------------------------------
            // Not sure, but it looks like we do not need 
            // to free HGLOBAL because Clipboard is now 
            // responsible for the copied data. (?)
            //
            // Otherwise the second call will crash
            // the app with a Win32 exception 
            // inside OpenClipboard() function
            //-------------------------------------------
            // Marshal.FreeHGlobal(global);
    
            return true;
        }
    }
    
    0 讨论(0)
提交回复
热议问题