简体   繁体   中英

How to copy, paste, cut in FastColoredTextBox?

I need three functions: Copy, Paste, Cut ,

For a FastColoredTextBox .. so far with my methods, the job is done but afterwards,

the cursor's position get changed and I got no clue on how to keep it where it

was before.

Here's my methods:

    private void OnMouseMenuCut(object sender, EventArgs e)
    {
        var sPoint = rtbScript.SelectionStart;
        var ePoint = rtbScript.SelectionLength;

        var text = rtbScript.SelectedText;
        rtbScript.Text = rtbScript.Text.Remove(sPoint, ePoint);

        Clipboard.SetText(text.Replace("\n", "\r\n"));
        rtbScript.Text = rtbScript.Text.Insert(sPoint, text);
    }

    private void OnMouseMenuCopy(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(rtbScript.SelectedText)) return;
        Clipboard.SetText(rtbScript.SelectedText.Replace("\n", "\r\n"));

    }

    private void OnMouseMenuPaste(object sender, EventArgs e)
    {
        if (!Clipboard.ContainsText()) return;
        var index = rtbScript.SelectionStart;

        rtbScript.Text = rtbScript.Text.Insert(index, Clipboard.GetText());
    }

Also, If there's a better way to do those functions, please post..

Thanks!

For a RichTextBox your code has more issues than loosing the Cursor position, It also looses all formatting! Here are versions that should work better:

    private void OnMouseMenuCut(object sender, EventArgs e)
    {
        var sPoint = rtbScript.SelectionStart;
        var text = rtbScript.SelectedText;

        rtbScript.Cut();

        Clipboard.SetText(text.Replace("\n", "\r\n"));
        rtbScript.SelectionStart = sPoint;
    }

    private void OnMouseMenuCopy(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(rtbScript.SelectedText)) return;
        Clipboard.SetText(rtbScript.SelectedText.Replace("\n", "\r\n"));
    }

    private void OnMouseMenuPaste(object sender, EventArgs e)
    {
        if (!Clipboard.ContainsText()) return;
        var index = rtbScript.SelectionStart;

        rtbScript.SelectedText = Clipboard.GetText();
        rtbScript.SelectionStart = index + Clipboard.GetText().Length;
    }

Note: You must never change the Text property of a RTB or else you will mess up the formating!

Since you wrote that this also works with your FastColoredTextBox I have undeleted the solution..

In the current version of FCTB, these methods already exist inside the FCTB.cs file. They just need to be linked up.

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