问题
Is there a way to preserve the contents of the clipboard? I tried the following code but it doesn't work.
Dim iData As IDataObject = Clipboard.GetDataObject()
...(use clipboard)
Clipboard.SetDataObject(iData)
Thank you.
回答1:
The easiest way to preserve the contents of the clipboard is to leave the clipboard alone. The clipboard is meant as a temporary storage area for the user, not for applications, so likely what you are trying to do has better solutions than to clobber the clipboard.
回答2:
You can use the OpenClipboard and CloseClipboard. According to MSDN opening the clipboard will keep other applications from changing the data.
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool CloseClipboard();
回答3:
In what way did your code above not work? When I try the equivalent code in C# I get a "CloseClipboard Failed (Exception from HRESULT: 0x800401D4 (CLIPBRD_E_CANT_CLOSE))" exception on calling Clipboard.SetDataObject(iData).
However, the following workaround does the job for me:
// save
Dictionary<String, Object> d = new Dictionary<String, Object>();
IDataObject ido = Clipboard.GetDataObject();
foreach (String s in ido.GetFormats(false))
d.Add(s, ido.GetData(s));
// ...
// restore
var da = new DataObject();
foreach (String s in d.Keys)
da.SetData(s, d[s]);
Clipboard.SetDataObject(da);
回答4:
I agree that the context is important. In my case, I wanted to paste a formatted, dynamically filled-in cover page document onto the front of some dynamically generated text (all in MS Word). Here's the solution I found (using VSTO and C#):
object start = 0;
Word.Range startRng = a_TreatedDocument.Range(ref start, ref start);
startRng.FormattedText = a_CoverPageDocument.Content.FormattedText;
Note, this works with tables and formatted text.
来源:https://stackoverflow.com/questions/923323/how-to-preserve-the-contents-of-the-clipboard