public static string GetClipboardText() { IntPtr hInstance = IntPtr.Zero; ClipboardNativeMethods.OpenClipboard(hInstance); IntPtr buffer = ClipboardNativeMethods.GetClipboardData(13); string text = Marshal.PtrToStringUni(buffer); ClipboardNativeMethods.CloseClipboard(); return(text); }
public static bool SetClipboardText(string text) { if (!ClipboardNativeMethods.OpenClipboard(IntPtr.Zero)) { return(false); } ClipboardNativeMethods.EmptyClipboard(); IntPtr alloc = MemoryNativeMethods.GlobalAlloc(MemoryNativeMethods.GMEM_MOVEABLE | MemoryNativeMethods.GMEM_DDESHARE, (UIntPtr)(sizeof(char) * (text.Length + 1))); IntPtr gLock = MemoryNativeMethods.GlobalLock(alloc); if ((int)text.Length > 0) { Marshal.Copy(text.ToCharArray(), 0, gLock, text.Length); } MemoryNativeMethods.GlobalUnlock(alloc); ClipboardNativeMethods.SetClipboardData(13, alloc); ClipboardNativeMethods.CloseClipboard(); return(true); }