简体   繁体   English

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

[英]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.我打算让字符串 s 成为要添加的字符串。

However, the RichTextBox in System.Windows.Forms does NOT contain a CaretPosition.但是,System.Windows.Forms 中的 RichTextBox 不包含 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.我发现 2010 年的一篇文章建议您使用 System.Windows.Control,但是,在 .Net Core 中不再可以访问它,这取决于演示框架。

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?那么,有什么方法可以在.net core 中实现我的目标(在鼠标光标后插入一个字符串,在富文本框中)?

Updated2:更新2:

Use the following code to fully satisfy the richtextbox of the text text environment.:使用如下代码完全满足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

Updated1:更新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();
}

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.根据您的需要自行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM