Home > Software design >  Adding text (Or getting CaretPosition) of RichTextBox in .Net Core
Adding text (Or getting CaretPosition) of RichTextBox in .Net Core

Time:05-31

I have a basic text editor app, and I aim to add a feature where the user can click a button and add premade text after where their cursor is.

I currently have this (using some code I found online)

richTextBox1.CaretPosition.InsertTextInRun(s);

I intend for the string s to be the string to be added.

However, the RichTextBox in System.Windows.Forms does NOT contain a CaretPosition. I found one post from 2010 suggesting you use System.Windows.Control, however, that is no longer accessible in .Net Core, it depends on presentation framework.

So, is there any way I could get my goal (inserting a string after the mouse cursor, in a rich text box), in .net core?

CodePudding user response:

Updated2:

Use the following code to fully satisfy the richtextbox of the text text environment.:

richTextBox1.Select(richTextBox1.SelectionStart, richTextBox1.TextLength);//Select everything after the cursor
string tmp = richTextBox1.SelectedText;//Copy them
richTextBox1.SelectedText = "";//Set to null
richTextBox1.AppendText("Hello world" tmp);//Add the target string and add the original text

Updated1:

// Determine if there is any text in the Clipboard to paste into the text box.
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{
    IDataObject dataObject = Clipboard.GetDataObject();
    Clipboard.SetDataObject("Hello World");
    richTextBox1.Paste();
    Clipboard.SetDataObject(dataObject);
}
else
{
    Clipboard.SetDataObject("Hello World");
    richTextBox1.Paste();
}

This action preserves the contents of the original pasteboard.

Only works if the clipboard is data. I will continue to update after I think about it.

Original: You only need to use the clipboard and enter image description here

Change it yourself according to your needs.

  • Related