当我尝试使用本机方法将字符串设置到剪贴板时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()
来做到这一点吗?为什么?
谢谢