public void PutText(string text) { if (!Open()) { // Technically this is a reason to throw exception, but it should be rare and it will indicate // that clipboard is being heavily used and content of the clipboard might be unpredictable even if Open succeeds. return; } IntPtr dataHandle = IntPtr.Zero; try { Win32API.EmptyClipboard(); dataHandle = Win32API.GlobalAlloc(GlobalAllocFlags.GMEM_MOVEABLE, (IntPtr)((text.Length + 1) * sizeof(char))); if (dataHandle == IntPtr.Zero) { throw new IOException("Failed to allocate memory for the clipboard data."); } IntPtr dataPtr = Win32API.GlobalLock(dataHandle); try { Marshal.Copy(text.ToCharArray(), 0, dataPtr, text.Length); Marshal.WriteInt16(dataPtr, sizeof(char) * text.Length, '\0'); } finally { Win32API.GlobalUnlock(dataHandle); } if (Win32API.SetClipboardData(Win32ClipboardFormat.CF_UNICODETEXT, dataHandle) != IntPtr.Zero) { // If SetClipboardData succeeds, then handle ownership is transferred to the system and it should not be freed by the application. dataHandle = IntPtr.Zero; } } finally { Win32API.CloseClipboard(); if (dataHandle != IntPtr.Zero) { Win32API.GlobalFree(dataHandle); } } }