使用SetClipboardData的c#失败,ERROR_INVALID_HANDLE

时间:2015-08-19 15:14:44

标签: c# marshalling clipboard copymemory

当我尝试使用本机方法SetClipboardData将字符串设置为剪贴板时。它失败并使用ERROR_INVALID_HANDLE方法获取错误代码6 GetLastError()。我无法找出它是如何失败的,这是代码:

                string copyMessage = "need copy to clipboard";
                const int GMEM_MOVABLE = 0x0002;
                const int GHND = GMEM_MOVABLE;

                uint format;
                uint bytes;
                IntPtr hGlobal = IntPtr.Zero;
                format = CF_UNICODETEXT;

                byte[] copyMessageBytes = Encoding.Unicode.GetBytes(copyMessage + "\0");

                // IMPORTANT: SetClipboardData requires memory that was acquired with GlobalAlloc using GMEM_MOVABLE.
                hGlobal = GlobalAlloc(GHND, (UIntPtr)copyMessageBytes.Length);
                if (hGlobal == IntPtr.Zero)
                {
                    return false;
                }
                Marshal.Copy(copyMessageBytes, 0, hGlobal, copyMessageBytes.Length);

                if (SetClipboardData(format, hGlobal).ToInt64() != 0) // code fails here
                {
                    // IMPORTANT: SetClipboardData takes ownership of hGlobal upon success.
                    hGlobal = IntPtr.Zero;
                }
                else
                {
                    return false;
                }

我使用Marshal.Copy(byte[] source, int startIndex, IntPtr destination, int length)将字节复制到hGlobal,是不是? 在这种情况下,剂量我必须使用本机方法CopyMemory()来做到这一点?为什么呢?

THX

1 个答案:

答案 0 :(得分:0)

我找到了解决方法。这是因为我按GlobalAlloc()分配内存,然后需要在复制数据之前调用GlobalLock(),然后需要在复制后调用GlobalUnlock()