C#控制台程序无法获取剪贴板内容问题求助
解决C#控制台程序无法读取剪贴板内容的问题
问题根源
控制台程序默认主线程为**MTA(多线程单元)模式,但System.Windows.Forms.Clipboard的操作要求线程处于STA(单线程单元)**模式;同时控制台程序没有Windows Forms的消息循环,这会导致剪贴板读取操作失效,返回空字符串。
解决方案
1. 设置主线程为STA模式
在Main方法上添加[STAThread]特性,强制线程以STA模式运行。
2. 初始化Windows Forms环境
在读取剪贴板前,调用Application.EnableVisualStyles()和Application.SetCompatibleTextRenderingDefault(false),初始化必要的消息循环和Forms运行环境。
修改后的完整代码
using System; using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; namespace ConsoleApp11 { internal class Program { [STAThread] // 关键:将主线程设置为STA模式 static void Main(string[] args) { GetClipboard(); Matcher(); Console.ReadLine(); } static void Matcher() { string filePath = "C:\\Users\\bener\\Downloads\\wordlist.txt"; string fileContents = File.ReadAllText(filePath); string pattern = @"\b\w+mb\b"; Regex regex = new Regex(pattern); MatchCollection matches = regex.Matches(fileContents); foreach (Match match in matches) { Console.WriteLine(match.Value); } } static string GetClipboard() { // 初始化Windows Forms环境,建立消息循环 Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); string clipboardContent = Clipboard.GetText(TextDataFormat.Text); Console.WriteLine("Clipboard Content: " + clipboardContent); return clipboardContent; } } }
额外注意事项
如果项目未引用System.Windows.Forms程序集,右键项目 -> 添加 -> 引用,在列表中找到并勾选System.Windows.Forms即可。
内容的提问来源于stack exchange,提问作者benbo
相关产品推荐
相关产品推荐

