简体   繁体   中英

Adding text (Or getting CaretPosition) of RichTextBox in .Net Core

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?

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 paste method to insert the specified string after the specified cursor.

 Clipboard.SetDataObject("Hello World");
 richTextBox1.Paste();
 Clipboard.Clear();

在此处输入图像描述

Change it yourself according to your needs.

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