//TODO: refactor this into custom service. public static byte[] GetClipboardDataBytes(uint format) { var dataPointer = GetClipboardDataPointer(format); var length = GetPointerDataLength(dataPointer); if (length == UIntPtr.Zero) { return(null); } var lockedMemory = GetLockedMemoryBlockPointer(dataPointer); if (lockedMemory == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error()); } var buffer = new byte[(int)length]; Marshal.Copy(lockedMemory, buffer, 0, (int)length); GeneralApi.GlobalUnlock(dataPointer); return(buffer); }
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."); } } }