Someone asked me how to insert text at a certain position in a richtextbox and then put the carat in the middle of the text that is inserted.
Like when you click the bold button you get [bold][/bold] or something like that where you can use the tags to enhance a message.
OK here is one way to accomplish
using System;
using System.Windows.Forms;
namespace TextBoxInsert
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonBold_Click(object sender, EventArgs e)
{
//when the user clicks the bold button, [Bold][/Bold] is inserted at the carat
//you may change to more preferred [b][/b] if needed just chnage the index += 6 to index += 3;
//and the carat is moved six spaces forward to the middle of the inserted text
//get the carat position
int index = richTextBox1.SelectionStart;
//insert the [Bold][/Bold] text at the carat position
richTextBox1.Text = richTextBox1.Text.Insert(index, "[Bold][/Bold]");
richTextBox1.SelectionStart = richTextBox1.TextLength;
//move the carat 6 spaces to the right
index += 6;
richTextBox1.SelectionStart = index;
//refocus to make carat blink
richTextBox1.Focus();
}
private void buttonItalics_Click(object sender, EventArgs e)
{
//see documentation above
int index = richTextBox1.SelectionStart;
richTextBox1.Text = richTextBox1.Text.Insert(index, "[Italic][/Italic]");
richTextBox1.SelectionStart = richTextBox1.TextLength;
index += 8;
richTextBox1.SelectionStart = index;
richTextBox1.Focus();
}
private void buttonUnderline_Click(object sender, EventArgs e)
{
//see documentation above
int index = richTextBox1.SelectionStart;
richTextBox1.Text = richTextBox1.Text.Insert(index, "[Underline][/Underline]");
richTextBox1.SelectionStart = richTextBox1.TextLength;
index += 11;
richTextBox1.SelectionStart = index;
richTextBox1.Focus();
}
}
}
Ken
