.Net Core - copy to clipboard?

前端 未结 6 933
耶瑟儿~
耶瑟儿~ 2020-12-08 04:28

Is it possible to copy something to the clipboard using .Net Core (in a platform-agnostic way)?

It seems that the Clipboard class is missing, and P/Invoking is

6条回答
  •  囚心锁ツ
    2020-12-08 04:55

    I was looking for the same thing. PowerShell is cross-platform, so I figured I would try that. I've only tested it on Windows though.

    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();
        }
    }
    

    Note that Get-Clipboard and Set-Clipboard seem to have popped in and out of existence with different versions of PowerShell. They were available in 5.1, not in 6, but are back again in 7.

提交回复
热议问题