Reputation: 1762
I got a problem with restoring the data here is the code if you read the comments then I ll think you ll understand the problem, and hopefuly know how to fix this.
var oldclip = System.Windows.Clipboard.GetDataObject(); //Here we save the clipboard
var oldpoint = CursorPosition;
CursorPosition = new System.Drawing.Point((Convert.ToInt32((rect.Width - rect.X) * 0.45) + rect.X), Convert.ToInt32((rect.Height - rect.Y) * 0.75) + rect.Y);
DoLeftMouseClick();
SetForegroundWindow(hwnd);
System.Threading.Thread.Sleep(20);
System.Windows.Forms.SendKeys.SendWait("^a^c{ESCAPE}"); // here we go select all text and then copy it to the clipboard
if (System.Windows.Clipboard.GetDataObject().GetDataPresent(DataFormats.Text)) //if the clipboard has text then we do something with it to get that info in the blabla here
{
//...blabla //
}
System.Windows.Clipboard.SetDataObject(oldclip); // HERE I want to restore the clipboard but that fails! After this when I CTRL+P(paste) then it returns nothing,(while it should still have the same "oldclip" data no??
EDIT: I got a better idea how to explain my problem. Lets say I got 2 buttons, button save & button restore. We got a variable:
IDataObject oldclip;
Button save code is:
oldclip = System.Windows.Clipboard.GetDataObject();
The we got the restore button code
System.Windows.Clipboard.SetDataObject(oldclip);
Now I copy some text "randomtext123". I press the save button. Then I go and copy some other text "otherrandomtext". Now if I press the restore button, I want the clipboard data to be "randomtext123" again but this doesn t happen.(Because if I paste after the resto button it doesn t do anything, like there is nothing on the clipboard). Hope you understand the problem better now :)
Upvotes: 1
Views: 2674
Reputation: 734
This should produce the desired result:
public class ClipboardBackup
{
Dictionary<string, object> contents = new Dictionary<string,object>();
public void Backup()
{
contents.Clear();
IDataObject o = Clipboard.GetDataObject();
foreach (string format in o.GetFormats())
contents.Add(format, o.GetData(format));
}
public void Restore()
{
DataObject o = new DataObject();
foreach (string format in contents.Keys)
{
o.SetData(format, contents[format]);
}
Clipboard.SetDataObject(o);
}
}
P.S. you might not want to do this. See this answer: https://stackoverflow.com/a/2579846/305865
Upvotes: 3
Reputation: 67065
Per the MSDN documentation, if you want to use the system clipboard, you must set the permission to AllClipboard:
for permission to access data on the system Clipboard. Associated enumeration: AllClipboard
I just tested, and running this code in your codebase will fix the problem:
UIPermission clipBoard = new UIPermission(PermissionState.None);
clipBoard.Clipboard = UIPermissionClipboard.AllClipboard;
Upvotes: 0