You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 07:25:12