0
当我尝试使用本机方法SetClipboardData
设置字符串到剪贴板。它失败并且使用GetLastError()
方法获得错误代码6 ERROR_INVALID_HANDLE
。我无法找出它是如何失败的,这里是代码:c#使用SetClipboardData失败,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
,是不是? 在这种情况下,剂量I必须使用本机方法CopyMemory()
来做到这一点?为什么?
Thx