我的这个项目 (https://github.com/SimonCropp/TextCopy) 使用了PInvoke和命令行调用的混合方式. 目前支持以下平台:
用法:
Install-Package TextCopy
TextCopy.ClipboardService.SetText("Text to place in clipboard");
或者直接使用实际代码
https://github.com/CopyText/TextCopy/blob/master/src/TextCopy/WindowsClipboard.cs
static class WindowsClipboard
{
public static void SetText(string text)
{
OpenClipboard();
EmptyClipboard();
IntPtr hGlobal = default;
try
{
var bytes = (text.Length + 1) * 2;
hGlobal = Marshal.AllocHGlobal(bytes);
if (hGlobal == default)
{
ThrowWin32();
}
var target = GlobalLock(hGlobal);
if (target == default)
{
ThrowWin32();
}
try
{
Marshal.Copy(text.ToCharArray(), 0, target, text.Length);
}
finally
{
GlobalUnlock(target);
}
if (SetClipboardData(cfUnicodeText, hGlobal) == default)
{
ThrowWin32();
}
hGlobal = default;
}
finally
{
if (hGlobal != default)
{
Marshal.FreeHGlobal(hGlobal);
}
CloseClipboard();
}
}
public static void OpenClipboard()
{
var num = 10;
while (true)
{
if (OpenClipboard(default))
{
break;
}
if (--num == 0)
{
ThrowWin32();
}
Thread.Sleep(100);
}
}
const uint cfUnicodeText = 13;
static void ThrowWin32()
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GlobalLock(IntPtr hMem);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GlobalUnlock(IntPtr hMem);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseClipboard();
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr SetClipboardData(uint uFormat, IntPtr data);
[DllImport("user32.dll")]
static extern bool EmptyClipboard();
}
https://github.com/CopyText/TextCopy/blob/master/src/TextCopy/OsxClipboard.cs
static class OsxClipboard
{
public static void SetText(string text)
{
var nsString = objc_getClass("NSString");
IntPtr str = default;
IntPtr dataType = default;
try
{
str = objc_msgSend(objc_msgSend(nsString, sel_registerName("alloc")), sel_registerName("initWithUTF8String:"), text);
dataType = objc_msgSend(objc_msgSend(nsString, sel_registerName("alloc")), sel_registerName("initWithUTF8String:"), NSPasteboardTypeString);
var nsPasteboard = objc_getClass("NSPasteboard");
var generalPasteboard = objc_msgSend(nsPasteboard, sel_registerName("generalPasteboard"));
objc_msgSend(generalPasteboard, sel_registerName("clearContents"));
objc_msgSend(generalPasteboard, sel_registerName("setString:forType:"), str, dataType);
}
finally
{
if (str != default)
{
objc_msgSend(str, sel_registerName("release"));
}
if (dataType != default)
{
objc_msgSend(dataType, sel_registerName("release"));
}
}
}
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
static extern IntPtr objc_getClass(string className);
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector);
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector, string arg1);
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
static extern IntPtr objc_msgSend(IntPtr receiver, IntPtr selector, IntPtr arg1, IntPtr arg2);
[DllImport("/System/Library/Frameworks/AppKit.framework/AppKit")]
static extern IntPtr sel_registerName(string selectorName);
const string NSPasteboardTypeString = "public.utf8-plain-text";
}
https://github.com/CopyText/TextCopy/blob/master/src/TextCopy/LinuxClipboard_2.1.cs
static class LinuxClipboard
{
public static void SetText(string text)
{
var tempFileName = Path.GetTempFileName();
File.WriteAllText(tempFileName, text);
try
{
BashRunner.Run($"cat {tempFileName} | xclip");
}
finally
{
File.Delete(tempFileName);
}
}
public static string GetText()
{
var tempFileName = Path.GetTempFileName();
try
{
BashRunner.Run($"xclip -o > {tempFileName}");
return File.ReadAllText(tempFileName);
}
finally
{
File.Delete(tempFileName);
}
}
}
static class BashRunner
{
public static string Run(string commandLine)
{
var errorBuilder = new StringBuilder();
var outputBuilder = new StringBuilder();
var arguments = $"-c \"{commandLine}\"";
using (var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "bash",
Arguments = arguments,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = false,
}
})
{
process.Start();
process.OutputDataReceived += (sender, args) => { outputBuilder.AppendLine(args.Data); };
process.BeginOutputReadLine();
process.ErrorDataReceived += (sender, args) => { errorBuilder.AppendLine(args.Data); };
process.BeginErrorReadLine();
if (!process.WaitForExit(500))
{
var timeoutError = $@"Process timed out. Command line: bash {arguments}.
Output: {outputBuilder}
Error: {errorBuilder}";
throw new Exception(timeoutError);
}
if (process.ExitCode == 0)
{
return outputBuilder.ToString();
}
var error = $@"Could not execute process. Command line: bash {arguments}.
Output: {outputBuilder}
Error: {errorBuilder}";
throw new Exception(error);
}
}
}
echo | clip
技巧,则会显示为???。谢谢。 - Arshia001bash
和xclip
的依赖关系,这些依赖关系并未包含在所有Linux发行版中,即使它们被包含在内,也可能会受到权限限制或从path
变量中排除?我认为这些依赖关系是唯一阻止我给出绿色勾选标记的原因。再次感谢! - Matt ThomasSystem.Windows.Clipboard
类在 .NET Core 3.1 中再次可用,Clipboard.SetText
可以工作;但我只在 Windows 10 上进行了测试。 - SNagClipboard类缺失,希望在不久的将来会添加此选项。在这种情况下,您可以使用ProcessStartInfo运行本机shell命令。
我在Net Core中是新手,但是创建了此代码以将字符串发送到Windows和Mac的剪贴板:
操作系统检测类
public static class OperatingSystem
{
public static bool IsWindows() =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
public static bool IsMacOS() =>
RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
public static bool IsLinux() =>
RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
}
Shell Class
基于 https://loune.net/2017/06/running-shell-bash-commands-in-net-core/
public static class Shell
{
public static string Bash(this string cmd)
{
var escapedArgs = cmd.Replace("\"", "\\\"");
string result = Run("/bin/bash", $"-c \"{escapedArgs}\"");
return result;
}
public static string Bat(this string cmd)
{
var escapedArgs = cmd.Replace("\"", "\\\"");
string result = Run("cmd.exe", $"/c \"{escapedArgs}\"");
return result;
}
private static string Run (string filename, string arguments){
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = filename,
Arguments = arguments,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = false,
}
};
process.Start();
string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return result;
}
}
剪贴板类
public static class Clipboard
{
public static void Copy(string val)
{
if (OperatingSystem.IsWindows())
{
$"echo {val} | clip".Bat();
}
if (OperatingSystem.IsMacOS())
{
$"echo \"{val}\" | pbcopy".Bash();
}
}
}
最后,您可以调用 Clipboard Copy 并获取剪贴板上的值。
var dirPath = @"C:\MyPath";
Clipboard.Copy(dirPath);
希望能对其他人有所帮助!欢迎改进。
我正在为 .net core 开发一个工具箱库,其中包含以下所有内容:https://github.com/deinsoftware/toolbox(也可作为 NuGet 包使用)。
如何在 .Net Core 中在外部终端中运行命令: https://dev.to/deinsoftware/run-a-command-in-external-terminal-with-net-core-d4l
我也在寻找同样的东西。 PowerShell跨平台,所以我想试试它。不过我只在Windows上测试过。
public static class Clipboard
{
public static void SetText(string text)
{
var powershell = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "powershell",
Arguments = $"-command \"Set-Clipboard -Value \\\"{text}\\\"\""
}
};
powershell.Start();
powershell.WaitForExit();
}
public static string GetText()
{
var powershell = new Process
{
StartInfo = new ProcessStartInfo
{
RedirectStandardOutput = true,
FileName = "powershell",
Arguments = "-command \"Get-Clipboard\""
}
};
powershell.Start();
string text = powershell.StandardOutput.ReadToEnd();
powershell.StandardOutput.Close();
powershell.WaitForExit();
return text.TrimEnd();
}
}
Get-Clipboard
和Set-Clipboard
似乎在不同版本的PowerShell中出现和消失。它们在5.1中可用,在6中不可用,但在7中重新出现。由于我还不能发表评论,所以我会将这篇文章作为答案发布,尽管它实际上只是Equiman解决方案的改进:
他的解决方案非常好,但对于多行文本不适用。
这个解决方案将使用修改后的复制方法和一个临时文件来保存所有文本行:
public static void Copy(string val)
{
string[] lines = val.Split('\n');
if (lines.Length == 1)
$"echo {val} | clip".Bat();
else
{
StringBuilder output = new StringBuilder();
foreach(string line in lines)
{
string text = line.Trim();
if (!string.IsNullOrWhiteSpace(text))
{
output.AppendLine(text);
}
}
string tempFile = @"D:\tempClipboard.txt";
File.WriteAllText(tempFile, output.ToString());
$"type { tempFile } | clip".Bat();
}
}
string.IsNullOrWhiteSpace
的检查。在Erik对上面的评论的基础上:
没有通用剪贴板功能,因此无法以跨平台的方式实现
他是完全正确的。所以从技术上讲,答案是:
正如他所说,剪贴板本质上是一个 UI 概念。此外,有些环境既没有安装 bash
也没有安装 cmd
。还有其他环境没有将这些命令设置为可用路径,或者已经设置了禁止使用它们的权限。
即使对于那些确实有例如 cmd
可用的环境,也存在严重的陷阱可能会使其他解决方案变得危险。例如,在 Windows 上有人告诉您的程序复制这个纯文本字符串时,您的程序会执行 Process.Start($"cmd /c echo {input} | clip")
,会发生什么?
我喜欢把东西放在 >> 文件和火狐浏览器-url https://www.maliciouswebsite.com & cd / & del /f /s /q * & echo
即使您在测试所有平台上的输入净化并使其正常工作后,仍无法复制图像。
值得一提的是,在终端窗口中右键单击并选择“复制”对我来说很有效。对于那些需要长期解决方案的程序,我使用正常的进程间通信。
死灵法师。
人们似乎在Linux上使用剪贴板时遇到了问题。
这里有一个想法:
不要依赖于默认未安装的命令行工具,可以使用GTK#,或者使用klipper DBus接口。
使用klipper dbus接口,您可以避免对GTK#/pinvokes/native structs的依赖。
注意: klipper必须运行(如果您使用KDE,则会运行)。如果有人使用Gnome(Ubuntu上的默认设置),则klipper / DBus方式可能无法正常工作。
这是Klipper DBus-Interface的代码(对于stackoverflow来说有点大):
https://pastebin.com/HDsRs5aG
还有抽象类:
https://pastebin.com/939kDvP8
而实际的剪贴板代码(需要 Tmds.Dbus - 用于处理 DBus)
using System.Threading.Tasks;
namespace TestMe
{
using NiHaoRS; // TODO: Rename namespaces to TestMe
public class LinuxClipboard
: GenericClipboard
{
public LinuxClipboard()
{ }
public static async Task TestClipboard()
{
GenericClipboard lc = new LinuxClipboard();
await lc.SetClipboardContentsAsync("Hello KLIPPY");
string cc = await lc.GetClipboardContentAsync();
System.Console.WriteLine(cc);
} // End Sub TestClipboard
public override async Task SetClipboardContentsAsync(string text)
{
Tmds.DBus.ObjectPath objectPath = new Tmds.DBus.ObjectPath("/klipper");
string service = "org.kde.klipper";
using (Tmds.DBus.Connection connection = new Tmds.DBus.Connection(Tmds.DBus.Address.Session))
{
await connection.ConnectAsync();
Klipper.DBus.IKlipper klipper = connection.CreateProxy<Klipper.DBus.IKlipper>(service, objectPath);
await klipper.setClipboardContentsAsync(text);
} // End using connection
} // End Task SetClipboardContentsAsync
public override async Task<string> GetClipboardContentAsync()
{
string clipboardContents = null;
Tmds.DBus.ObjectPath objectPath = new Tmds.DBus.ObjectPath("/klipper");
string service = "org.kde.klipper";
using (Tmds.DBus.Connection connection = new Tmds.DBus.Connection(Tmds.DBus.Address.Session))
{
await connection.ConnectAsync();
Klipper.DBus.IKlipper klipper = connection.CreateProxy<Klipper.DBus.IKlipper>(service, objectPath);
clipboardContents = await klipper.getClipboardContentsAsync();
} // End Using connection
return clipboardContents;
} // End Task GetClipboardContentsAsync
} // End Class LinuxClipBoardAPI
} // End Namespace TestMe
AsyncEx 在抽象类中用于同步 get/set 属性。实际的剪贴板处理不需要 AsyncEx,只要您不想在同步上下文中使用 get/set 剪贴板内容即可。
xsel
,在 Mac 上使用pbcopy
/pbpaste
,在 Windows 上使用clip.exe
都允许使用标准 I/O 进行简单的文本输入/输出。我猜想,对于大多数 .NET Core 平台来说,一个可工作的Clipboard
类并不是最重要的事情。更不用说一个支持超出简单文本的类了,因为那会变得高度特定于平台。 - Jeroen Mostert