问题
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