/// <summary> /// Empty the Clipboard and Restore to system clipboard data contained in a collection of ClipData objects /// </summary> /// <param name="clipData">The collection of ClipData containing data stored from clipboard</param> /// <returns></returns> public static bool SetClipboard(ReadOnlyCollection <ClipboardData> clipData) { //Open clipboard to allow its manipultaion if (!ClipboardApi.OpenClipboard(IntPtr.Zero)) { return(false); } //Clear the clipboard EmptyClipboard(); //Get an Enumerator to iterate into each ClipData contained into the collection IEnumerator <ClipboardData> cData = clipData.GetEnumerator(); while (cData.MoveNext()) { ClipboardData cd = cData.Current; //Get the pointer for inserting the buffer data into the clipboard IntPtr alloc = MemoryApi.GlobalAlloc(MemoryApi.GMEM_MOVEABLE | MemoryApi.GMEM_DDESHARE, cd.Size); IntPtr gLock = MemoryApi.GlobalLock(alloc); //Clopy the buffer of the ClipData into the clipboard if ((int)cd.Size > 0) { Marshal.Copy(cd.Buffer, 0, gLock, cd.Buffer.GetLength(0)); } else { } //Release pointers MemoryApi.GlobalUnlock(alloc); ClipboardApi.SetClipboardData(cd.Format, alloc); } ; //Close the clipboard to realese unused resources ClipboardApi.CloseClipboard(); return(true); }
void InjectClipboardData(IClipboardData clipboardData) { using (var memoryHandle = memoryHandleFactory.AllocateInMemory(clipboardData.RawData)) { var globalPointer = AllocateInMemory(clipboardData); var target = GeneralApi.GlobalLock(globalPointer); if (target == IntPtr.Zero) { throw new InvalidOperationException("Could not allocate memory."); } GeneralApi.CopyMemory(target, memoryHandle.Pointer, (uint)clipboardData.RawData.Length); GeneralApi.GlobalUnlock(target); if (ClipboardApi.SetClipboardData(clipboardData.RawFormat, globalPointer) == IntPtr.Zero) { GeneralApi.GlobalFree(globalPointer); throw new Exception("Could not set clipboard data."); } } }