2012-04-07 19 views
1

我遇到了恢復數據的問題,這裏是代碼,如果您閱讀註釋,然後我會認爲您會理解問題,並希望知道如何解決此問題。剪貼板無法使用setdataobject恢復數據

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?? 

編輯:我有一個更好的主意如何解釋我的問題。可以說我有2個按鈕,按鈕保存&按鈕恢復。 我們得到了一個變量:

IDataObject oldclip; 

按鈕保存代碼:

oldclip = System.Windows.Clipboard.GetDataObject(); 

的,我們得到了恢復按鈕的代碼

System.Windows.Clipboard.SetDataObject(oldclip); 

現在我複製一些文字 「randomtext123」。我按下保存按鈕。然後,我去複製一些其他文字「otherrandomtext」。 現在,如果我按下恢復按鈕,我希望剪貼板數據再次成爲「randomtext123」,但是這不會發生(因爲如果我在恢復按鈕後粘貼,它不會執行任何操作,就像剪貼板上沒有任何內容一樣)。希望你明白這個問題現在好了:)

回答

0

MSDN documentation,如果你要使用系統剪貼板,則必須將權限設置爲AllClipboard:

的權限訪問系統上的數據剪貼板。相關 枚舉:AllClipboard

我只是測試,並運行在你的代碼庫中的代碼即可解決問題:

UIPermission clipBoard = new UIPermission(PermissionState.None); 
    clipBoard.Clipboard = UIPermissionClipboard.AllClipboard; 
+0

當我這樣做,然後我能夠粘貼,但只能在窗體(在文本框)不在外面^^? (所以如果我去文本框並粘貼它的作品,如果我去鉻和粘貼,它不起作用) – Maximc 2012-04-07 18:37:01

+0

@Maximc你可以用你正在嘗試更新你的問題的代碼?正如我所說,我測試了這個,它爲我工作 – 2012-04-07 18:38:13

+0

奧克編輯的問題,希望你現在瞭解它:)。 – Maximc 2012-04-07 18:48:09

3

這應該產生期望的結果:

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); 
    } 
} 

附:你可能不想這樣做。看到這個答案:https://stackoverflow.com/a/2579846/305865