简体   繁体   English

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

[英]C# WPF Clipboard.SetText() not working properly

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.但只有 "\\t\\t\\t\\r\\n" 存储在我的剪贴板中。 This is the only code that uses the Clipboard in my application and it gets called.这是在我的应用程序中使用剪贴板并被调用的唯一代码。

*Edit: Found the error. *编辑:发现错误。 I used the above code for a copy-paste operation in a DataGridRow.我将上面的代码用于 DataGridRow 中的复制粘贴操作。 This works for that:这适用于:

 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 中复制某物并再次覆盖我的文本。

Clearing the Clipboard is redundant as SetText does that automatically for you.清除剪贴板是多余的,因为 SetText 会自动为您执行此操作。

This is what I usually use:这是我通常使用的:

Clipboard.SetText(msg, TextDataFormat.Text);

or

Clipboard.SetText(msg,TextDataFormat.UnicodeText);

Reference is here参考在这里

    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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM