C#如何保存剪贴板内容,在使用后恢复。
2015-06-03 14:25
465 查看
C# clipboard类封装了对剪贴板的操作,一般使用没有问题。但由于clipboard封装的数据类型有限,对于一些自定义类型的剪贴板数据,如果想占用剪贴板并在使用后原样恢复剪贴板的数据就会产生问题。试验了很多方法后,尝试学习别人C++的思路。使用winapi来处理剪贴本解决问题。
using System; using System.Runtime.InteropServices; using System.Collections.Generic; namespace 学习 { class MyClip { [DllImport("user32.dll", CharSet = CharSet.Auto)] static public extern IntPtr SetClipboardData(uint Format, IntPtr hData); [DllImport("user32.dll", SetLastError = true)] static extern uint EnumClipboardFormats(uint format); //枚举剪贴板内数据类型 [DllImport("user32.dll", SetLastError = true)] private static extern Int32 OpenClipboard(IntPtr hWndNewOwner); [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr GetClipboardData(uint uFormat); [DllImport("user32.dll", SetLastError = true)] private static extern Int32 CloseClipboard(); [DllImport("kernel32.dll", SetLastError = true)] private static extern Int32 GlobalLock(IntPtr hMem); [DllImport("kernel32.dll", SetLastError = true)] private static extern Int32 GlobalUnlock(IntPtr hMem); [DllImport("kernel32.dll")] public static extern uint GlobalSize(IntPtr hMem); /// <summary> /// 剪贴板数据保存目标数据列表 /// </summary> private static List<byte[]> bytes = new List<byte[]>(); /// <summary> /// 剪贴板数据类型列表 /// </summary> private static List<uint> formats = new List<uint>(); /// <summary> /// 保存剪贴板内容,返回真为成功,false为失败。 /// </summary> /// <returns></returns> public static bool saveClip() { bool fi = true; if (OpenClipboard((IntPtr)0) < 1) { fi = false; return false; } else { bytes.Clear(); formats.Clear(); } IntPtr hMem = IntPtr.Zero; IntPtr lpStr = IntPtr.Zero; uint uFormat = 0; while (fi) { uFormat = EnumClipboardFormats(uFormat);//枚举剪贴板所有数据类型 if (uFormat > 0) { formats.Add(uFormat); hMem = GetClipboardData(uFormat); lpStr = (IntPtr)GlobalLock(hMem); if (hMem != (IntPtr)0) { uint size = GlobalSize(hMem); IntPtr s = (IntPtr)GlobalLock(hMem); byte[] buffer = new byte[(int)size]; if (size > 0) { Marshal.Copy(s, buffer, 0, (int)size);//将剪贴板数据保存到自定义字节数组 } GlobalUnlock(hMem); bytes.Add(buffer); } } else { fi = false; } } CloseClipboard(); if (formats.Count>0) {return true;} else{return false;} } /// <summary> /// 恢复保存的数据 /// </summary> /// <returns></returns> public static bool restoreClip() { bool fi = true; if (formats.Count <= 0) { return false; } if (OpenClipboard((IntPtr)0) < 1) { fi = false; return false; } if (fi) { for (int i = 0; i < formats.Count; i++) { int size = bytes[i].Length; IntPtr si = Marshal.AllocHGlobal(size); if (size > 0) { Marshal.Copy(bytes[i], 0, si, size); } else { } SetClipboardData(formats[i], si); } } CloseClipboard(); if (formats.Count>0) {return true;} else{return false;} } } }