我怎么能复制一个字符串(例如“hello”)到系统剪贴板在c#,所以下次我按CTRL+V我会得到“hello”?
当前回答
我在这个问题上使用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。唯一的办法,经过大量研究。
其他回答
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;
}
如果你不想或者不能使用System.Windows.Forms,你可以使用Windows本地api: user32和剪贴板函数GetClipboardData和SetClipboardDat (pinvoke)
.NET 6包装器库可以在这里找到https://github.com/MrM40/WitWinClipboard/tree/main
对于控制台项目,您必须首先添加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!");
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因