C#Clipboard.GetText() [英] C# Clipboard.GetText()

查看:210
本文介绍了C#Clipboard.GetText()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能获得在非静态线程剪贴板文本?
我有一个解决方案,但我试图得到尽可能干净/最短途径。
结果正常调用时,它打开了一个空字符串。

How can I get the clipboard text in a non static thread? I have a solution but I'm trying to get the cleanest/shortest way possible. The results turn up as an empty string when calling it normally.

推荐答案

我想补充一个辅助方法,可以运行动作为MTA主线程中STA线程。
我想这可能是才达到它最彻底的方法。

I would add a helper method that can run an Action as an STA Thread within a MTA Main Thread. I think that is probably the cleanest way to achive it.

class Program
{
    [MTAThread]
    static void Main(string[] args)
    {
        RunAsSTAThread(
            () =>
            {
                Clipboard.SetText("Hallo");
                Console.WriteLine(Clipboard.GetText());
            });
    }

    /// <summary>
    /// Start an Action within an STA Thread
    /// </summary>
    /// <param name="goForIt"></param>
    static void RunAsSTAThread(Action goForIt)
    {
        AutoResetEvent @event = new AutoResetEvent(false);
        Thread thread = new Thread(
            () =>
            {
                goForIt();
                @event.Set();
            });
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        @event.WaitOne();
    }
}

这篇关于C#Clipboard.GetText()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆