简体   繁体   中英

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:

        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.

*Edit: Found the error. I used the above code for a copy-paste operation in a 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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