C#RichTextBox粘贴添加额外字符

时间:2018-02-25 19:34:52

标签: c# winforms richtextbox copy-paste

我的作业程序在richtextbox中有富文本的剪切,复制和粘贴方法。但是,当我复制然后粘贴时,我会获得额外的字符和数字粘贴,但我不知道它们来自哪里。

我的剪切,复制和粘贴方法是否不正确?我做了很多搜索,但我似乎无法确定问题。我的测试文件有单词" test"或"测试"在几行中,但是当我粘贴时,我会得到像" 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 个答案:

答案 0 :(得分:1)

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

示例

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