【发布时间】:2015-11-12 23:44:13
【问题描述】:
当我尝试使用本机方法 SetClipboardData 将字符串设置到剪贴板时。它失败并使用 GetLastError() 方法获得错误代码 6 ERROR_INVALID_HANDLE。我不知道它是如何失败的,这里是代码:
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() 来执行此操作吗?为什么?
谢谢
【问题讨论】:
标签: c# marshalling clipboard copymemory