Clipboard.GetText返回null(空字符串)空字符串、Clipboard、GetText、null

2023-09-02 21:24:12 作者:谁的年少不轻狂@

我的剪辑板是用文本填充,但是当我运行

My clip board is populated with text but when I run

string clipboardData = Clipboard.GetText(System.Windows.Forms.TextDataFormat.Text);

我找回一个空字符串。我把玩着各种形式的通话,包括:

I get back an empty string. I've toyed with various forms of the call including:

string clipboardData = Clipboard.GetText();
string clipboardData = Clipboard.GetText(System.Windows.Forms.TextDataFormat.UnicodeText);

但同样的结果。

but same result.

我失去了一些东西明显?

Am I missing something obvious?

感谢

推荐答案

您只能从一个STA线程访问剪贴板。里克·布鲁斯特就遇到了这个与一些重构普通编辑 - >粘贴命令,在Paint.NET。

You can only access the clipboard from an STA thread. Rick Brewster ran into this with some refactoring of the regular Edit->Paste command, in Paint.NET.

code:

IDataObject idat = null;
Exception threadEx = null;
Thread staThread = new Thread(
    delegate ()
    {
        try
        {
            idat = Clipboard.GetDataObject();
        }

        catch (Exception ex) 
        {
            threadEx = ex;            
        }
    });
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
// at this point either you have clipboard data or an exception

code是里克。 http://forums.getpaint.net/index.php?/topic/13712-/page__view__findpost__p__226140

更新:杰森 - 海涅取得加入()在代理以固定的暧昧方法错误。

Update: Jason Heine made a good point of adding () after delegate to fix the ambiguous method error.