簡體   English   中英

在 .Net Core 中添加 RichTextBox 的文本(或獲取 CaretPosition)

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

我有一個基本的文本編輯器應用程序,我的目標是添加一個功能,用戶可以單擊按鈕並在光標所在的位置添加預制文本。

我目前有這個(使用我在網上找到的一些代碼)

richTextBox1.CaretPosition.InsertTextInRun(s);

我打算讓字符串 s 成為要添加的字符串。

但是,System.Windows.Forms 中的 RichTextBox 不包含 CaretPosition。 我發現 2010 年的一篇文章建議您使用 System.Windows.Control,但是,在 .Net Core 中不再可以訪問它,這取決於演示框架。

那么,有什么方法可以在.net core 中實現我的目標(在鼠標光標后插入一個字符串,在富文本框中)?

更新2:

使用如下代碼完全滿足text文本環境的richtextbox:

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

更新1:

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

此操作會保留原始粘貼板的內容。

僅當剪貼板是數據時才有效。 我會在考慮之后繼續更新。

原文:只需要使用剪貼板和粘貼的方法在指定光標后插入指定字符串即可。

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

在此處輸入圖像描述

根據您的需要自行更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM