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