How can I copy a string (e.g "hello") to the System Clipboard in C#, so next time I press CTRL+V I'll get "hello"?
How can I copy a string (e.g "hello") to the System Clipboard in C#, so next time I press CTRL+V I'll get "hello"?
Clip.exe is an executable in Windows to set the clipboard. Note that this does not work for other operating systems other than Windows, which still sucks.
/// <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;
}
If you don't want to set the thread as STAThread, use Clipboard.SetDataObject(object sthhere):
Clipboard.SetDataObject("Yay! No more STA thread!");
On ASP.net web forms use in the @page AspCompat="true", add the system.windows.forms to you project. At your web.config add:
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
</appSettings>
Then you can use:
Clipboard.SetText(CreateDescription());
This works on .net core, no need to reference System.Windows.Forms
using Windows.ApplicationModel.DataTransfer;
DataPackage package = new DataPackage();
package.SetText("text to copy");
Clipboard.SetContent(package);
It works cross-platform. On windows, you can press windows + V to view your clipboard history
If you don't want too or cannot use System.Windows.Forms you can use the Windows native api: user32 and the clipboard functions GetClipboardData and SetClipboardDat (pinvoke)
A .NET 6 wrapper library can be found here https://github.com/MrM40/WitWinClipboard/tree/main