Why clipboard.setdataobject doesn't copy object to the clipboard in C#

女生的网名这么多〃 提交于 2021-01-29 18:21:55

问题


I have a win app (C#) that use clipboard to send and receive data to/from other applications. for example I want to use Word app in windows, I copy a text using c# to the clipboard, but when i want to simulate paste key (Stroke Ctrl+v) in c# , the clipboard is empty and i just got "v" as result. To copy to the clipboard i use the following code:

  public static void CopyToClipboard(string textForCopyToClipBoard)
  {
     Clipboard.Clear();
     Clipboard.SetDataObject(
     textForCopyToClipBoard, 
     true, 
     5, 
     200); 
   }

To simulate paste or stroke Ctrl+v, i use the following code

public static void PasteFromClipboard()
   {
        System.Windows.Forms.SendKeys.Send("^v");
   }

回答1:


Well , The Correct Code About The Putting Objects On Clipboard is:

Clipboard.SetText("hello");

You'll need to use the System.Windows.Forms or System.Windows namespaces for that.

You can only access the clipboard from an STA thread. Rick Brewster ran into this with some refactoring of the regular Edit->Paste command, in Paint.NET.

Code:

IDataObject idat = null;
Exception threadEx = null;
Thread staThread = new Thread(
    delegate ()
    {
        try
        {
            idat = Clipboard.GetDataObject();
        }

        catch (Exception ex) 
        {
            threadEx = ex;            
        }
    });
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
// at this point either you have clipboard data or an exception


来源:https://stackoverflow.com/questions/38421985/why-clipboard-setdataobject-doesnt-copy-object-to-the-clipboard-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!