【问题标题】:Clipboard fail to restore data with setdataobject剪贴板无法使用 setdataobject 恢复数据
【发布时间】:2012-04-07 17:44:12
【问题描述】:

我在恢复数据时遇到了问题,这里是代码,如果您阅读了 cmets,那么我认为您会理解这个问题,并希望知道如何解决这个问题。

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”,但这不会发生。(因为如果我在恢复按钮之后粘贴它不会做任何事情,就像剪贴板上什么都没有一样)。希望你现在更好地理解这个问题:)

【问题讨论】:

    标签: c# wpf clipboard


    【解决方案1】:

    这应该会产生预期的结果:

    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

    【讨论】:

      【解决方案2】:

      根据MSDN documentation,如果要使用系统剪贴板,必须将权限设置为AllClipboard:

      获得访问系统剪贴板上数据的权限。联系 枚举:AllClipboard

      我刚刚测试过,在您的代码库中运行此代码将解决问题:

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

      【讨论】:

      • 当我这样做时,我可以粘贴但只能在表单中(在文本框中)而不是在它之外^^? (所以如果我去文本框并粘贴它可以工作,如果我去 chrom 并粘贴,它就不起作用)
      • @Maximc 你能用你正在尝试的内容更新你问题中的代码吗?正如我所说,我对此进行了测试,它对我有用
      猜你喜欢
      • 2011-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      相关资源
      最近更新 更多