首页 文章

C#RichTextBox粘贴添加额外字符

提问于
浏览
1

我的分配程序具有富文本框中富文本的剪切,复制和粘贴方法 . 但是,当我复制然后粘贴时,我会得到额外的字符和数字粘贴,我不知道它们来自哪里 .

我的剪切,复制和粘贴方法是否不正确?我已经做了很多搜索,但我似乎无法确定问题 . 我的测试文件在几行中有单词“test”或“Testing”,但是当我粘贴时,我会粘贴“ng1033”之类的东西 .

private void cutText()
{
    Clipboard.Clear();
    if(desktopRichText.SelectionLength > 0)
    {
        //cut selected text to clipboard
        Clipboard.SetText(desktopRichText.SelectedRtf);
        desktopRichText.SelectedRtf = string.Empty;
    }
    else
    {
        MessageBox.Show("Please select text to modify");
    }

}

private void copyText()
{
    Clipboard.Clear();
    if(desktopRichText.SelectionLength > 0)
    {
        //copies selected text to clipboard
        Clipboard.SetText(desktopRichText.SelectedRtf);
    }
    else
    {
        MessageBox.Show("Please select text to modify");
    }

}

private void pasteText()
{
    if (Clipboard.ContainsText())
    {
        //pastes text on clipboard to richtextbox
        string cutText = Clipboard.GetText();
        desktopRichText.SelectedRtf = desktopRichText.SelectedRtf.Insert(desktopRichText.SelectionStart, cutText);
    }
    else
    {
        MessageBox.Show("Please select text to modify");
    }
}

1 回答

  • 1

    要在 RichTextBox 中复制,剪切或粘贴,请使用控件的相应方法:

    Example

    private void CopyButton_Click(object sender, EventArgs e)
    {
        if (richTextBox1.SelectionLength > 0)
            richTextBox1.Copy();
    }
    private void CutButton_Click(object sender, EventArgs e)
    {
        if (richTextBox1.SelectionLength > 0)
            richTextBox1.Cut();
    }
    private void PasteButton_Click(object sender, EventArgs e)
    {
        if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
            richTextBox1.Paste();
    }
    

相关问题