问题描述
我有一个win app(C#),它使用剪贴板向/从其他应用程序发送和接收数据。例如,我想在Windows中使用Word应用程序,我使用c#将文本复制到剪贴板,但是当我想在c#中模拟粘贴键(Stroke Ctrl + v)时,剪贴板是空的,我只是得到了v作为结果。
要复制到剪贴板,请使用以下代码:
I have a win app (C#) that use clipboard to send and receive data to/from other applications. for example i wnat 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(
textForCopyInClipBoard,
true,
5,
200);
}
要模拟粘贴或描边Ctrl + v,我使用以下代码
To simulate paste or stroke Ctrl+v, i use the following code
public static void PasteFromClipboard()
{
System.Windows.Forms.SendKeys.Send("^v");
}
我尝试过:
要复制到剪贴板,我尝试了以下方法
What I have tried:
To copy to the clipboard, I tried the following method
推荐答案
private void button2_Click(object sender, EventArgs e)
{
tbPasteIntoMe.Focus();
Clipboard.SetText("Hello there!");
SendKeys.Send("^v");
}
我的文本框获取字符串Hello there!没有问题。
但是......请记住SendKeys总是发送到Active应用程序 - 这可能属于你的应用程序,而不是你要粘贴的应用程序。这可能与你的问题有关...
但说实话,你不应该使用剪贴板,除非用户明确告诉你 - 很多如果你在没有事先询问的情况下覆盖他们放在剪贴板上的内容,那么用户(包括我)会非常非常恼火。
您可能应该找到更好的进程间通信方法 - 使用剪贴板是我称之为蛮力和无知的方法,通常意味着你的整个设计需要看。
And my textbox gets the string "Hello there!" without problems.
But...do remember that SendKeys always sends to the Active application - which is probably yours, not the one you want to paste into. This may have something to do with your problem...
But to be honest, you shouldn't use the clipboard unless the user has explicitly told you to - many users (including me) will get very, very annoyed if you overwrite what they have placed on the clipboard without asking them in advance.
You probably should find a better method for interprocess communications - using the clipboard is what I call a "brute force and ignorance" approach which generally means your whole design needs looking at.
这篇关于为什么clipboard.setdataobject不会在C#中将对象复制到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!