C# WPF Clipboard.SetText() 不能正常工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19490556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:54:34  来源:igfitidea点击:

C# WPF Clipboard.SetText() not working properly

c#.netwpfclipboard

提问by Florian Baierl

I have encountered a problem while using the Clipboard in a WPF Application: My code looks like this:

我在 WPF 应用程序中使用剪贴板时遇到问题:我的代码如下所示:

        var msg = "sample message for the clipboard";
        Clipboard.Clear();
        Clipboard.SetText(msg);

But only "\t\t\t\r\n" gets stored in my clipboard. This is the only code that uses the Clipboard in my application and it gets called.

但只有 "\t\t\t\r\n" 存储在我的剪贴板中。这是在我的应用程序中使用剪贴板并被调用的唯一代码。

*Edit: Found the error. I used the above code for a copy-paste operation in a DataGridRow. This works for that:

*编辑:发现错误。我将上面的代码用于 DataGridRow 中的复制粘贴操作。这适用于:

 private void OnCopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e)
    {
            var msg = "sample"
            e.ClipboardRowContent.Clear();
            e.ClipboardRowContent.Add(new DataGridClipboardCellContent(e.Item, (sender as DataGrid).Columns[0], msg));
    }

I guess the problem was that it automatically tried to copy sth out of my DataGrid after my Clipboard.SetText(..) and overwrote my text again.

我想问题在于它在我的 Clipboard.SetText(..) 之后自动尝试从我的 DataGrid 中复制某物并再次覆盖我的文本。

回答by Leon

Clearing the Clipboard is redundant as SetText does that automatically for you.

清除剪贴板是多余的,因为 SetText 会自动为您执行此操作。

This is what I usually use:

这是我通常使用的:

Clipboard.SetText(msg, TextDataFormat.Text);

Clipboard.SetText(msg, TextDataFormat.Text);

or

或者

Clipboard.SetText(msg,TextDataFormat.UnicodeText);

Clipboard.SetText(msg,TextDataFormat.UnicodeText);

Reference is here

参考在这里

回答by Manuel Alves

    protected void clipboardSetText(string inTextToCopy)
    {
        var clipboardThread = new Thread(() => clipBoardThreadWorker(inTextToCopy));
        clipboardThread.SetApartmentState(ApartmentState.STA);
        clipboardThread.IsBackground = false;
        clipboardThread.Start();
    }
    private void clipBoardThreadWorker(string inTextToCopy)
    {
        System.Windows.Clipboard.SetText(inTextToCopy);
    }