我怎么能复制一个字符串(例如“hello”)到系统剪贴板在c#,所以下次我按CTRL+V我会得到“hello”?
当前回答
对于控制台项目,您必须首先添加System.Windows.Forms引用。以下步骤在Visual Studio Community 2013和。net 4.5中工作:
在“解决方案资源管理器”中展开控制台项目。 右键单击引用,然后单击添加引用… 在“程序集”组中,在“框架”下,选择System.Windows.Forms。 单击OK。
然后,将下面的using语句添加到代码顶部的其他语句中:
using System.Windows.Forms;
然后,添加下列剪贴板之一。SetText语句到你的代码:
Clipboard.SetText("hello");
// OR
Clipboard.SetText(helloString);
最后,将STAThreadAttribute添加到Main方法中,以避免System.Threading.ThreadStateException:
[STAThreadAttribute]
static void Main(string[] args)
{
// ...
}
其他回答
我在这个问题上使用WPF c#处理剪贴板和System.Threading.ThreadStateException的经验是我的代码在所有浏览器上都正确工作:
Thread thread = new Thread(() => Clipboard.SetText("String to be copied to clipboard"));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join();
这篇文章的功劳在这里
但这只在本地主机上工作,所以不要在服务器上尝试这一点,因为它不会工作。
在服务器端,我使用zeroclipboard。唯一的办法,经过大量研究。
如果您不想将线程设置为STAThread,请使用Clipboard。SetDataObject sthhere(对象):
Clipboard.SetDataObject("Yay! No more STA thread!");
对于控制台项目,您必须首先添加System.Windows.Forms引用。以下步骤在Visual Studio Community 2013和。net 4.5中工作:
在“解决方案资源管理器”中展开控制台项目。 右键单击引用,然后单击添加引用… 在“程序集”组中,在“框架”下,选择System.Windows.Forms。 单击OK。
然后,将下面的using语句添加到代码顶部的其他语句中:
using System.Windows.Forms;
然后,添加下列剪贴板之一。SetText语句到你的代码:
Clipboard.SetText("hello");
// OR
Clipboard.SetText(helloString);
最后,将STAThreadAttribute添加到Main方法中,以避免System.Threading.ThreadStateException:
[STAThreadAttribute]
static void Main(string[] args)
{
// ...
}
这在。net core上工作,不需要引用System.Windows.Forms
using Windows.ApplicationModel.DataTransfer;
DataPackage package = new DataPackage();
package.SetText("text to copy");
Clipboard.SetContent(package);
它是跨平台的。在windows上,您可以按windows + V查看剪贴板历史记录
Clip.exe是Windows下用于设置剪贴板的可执行文件。注意,除了Windows之外,这并不适用于其他操作系统,Windows仍然很糟糕。
/// <summary>
/// Sets clipboard to value.
/// </summary>
/// <param name="value">String to set the clipboard to.</param>
public static void SetClipboard(string value)
{
if (value == null)
throw new ArgumentNullException("Attempt to set clipboard with null");
Process clipboardExecutable = new Process();
clipboardExecutable.StartInfo = new ProcessStartInfo // Creates the process
{
RedirectStandardInput = true,
FileName = @"clip",
};
clipboardExecutable.Start();
clipboardExecutable.StandardInput.Write(value); // CLIP uses STDIN as input.
// When we are done writing all the string, close it so clip doesn't wait and get stuck
clipboardExecutable.StandardInput.Close();
return;
}
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和