微軟官方文檔:https://docs.microsoft.com/en-us/dotnet/api/system.windows.clipboard?view=netframework-4.8
把文本複製到粘貼板
步驟如下:
1 新建控制檯項目,名爲獲取剪切板的內容
2 添加PresentationCore.dll引用
3 設置文本到粘貼板,編寫代碼如下(需要注意的是需要在Main方法上方加上[STAThread]):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace 獲取剪切板的內容
{
class Program
{
[STAThread]
static void Main(string[] args)
{
// For this example, the data to be placed on the clipboard is a simple
// string.
string textData = "I want to put this string on the clipboard.";
new Test().SetTextData(textData);
Console.ReadKey();
}
}
class Test
{
public void SetTextData(string textData)
{
// After this call, the data (string) is placed on the clipboard and tagged
// with a data format of "Text".
Clipboard.SetData(DataFormats.Text, (Object)textData);
}
}
}
4 從黏貼板獲取文本的代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace 獲取剪切板的內容
{
class Program
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine(new Test().GetTextData());
Console.ReadKey();
}
}
class Test
{
public string GetTextData() {
if (Clipboard.ContainsData(DataFormats.Text))
{
return Clipboard.GetText();
}
else {
return "";
}
}
}
}
獲取結果如下: