Display button in RichTextBox
How to display button
before the line where the pointer is set?
The button is currently displayed next to the clicked row.
private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
{
button2.Visible = true;
int index = richTextBox1.SelectionStart;
int line = richTextBox1.GetLineFromCharIndex(index);
button2.Visible = true;
int x = richTextBox1.Location.X - 10;
int y = 25;
for (int i = 0; i < richTextBox1.Lines.Length; i++)
{
button2.Location = new Point(280, Cursor.Position.Y - 170);
}
}
+3
source to share
2 answers
If you want to display the button "inside" richTextBox1
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
var pos = richTextBox1.GetPositionFromCharIndex(richTextBox1.SelectionStart);
if (pos.X > button2.Width + 4)
{
if (button2.Parent != richTextBox1)
{
button2.Parent.Controls.Remove(button2);
richTextBox1.Controls.Add(button2);
}
button2.Location = new Point(pos.X - button2.Width - 2, pos.Y);
}
else
{
if (button2.Parent == richTextBox1)
{
button2.Parent.Controls.Remove(button2);
richTextBox1.Parent.Controls.Add(button2);
}
button2.Location = new Point(richTextBox1.Left - button2.Width - 2, pos.Y + richTextBox1.Top);
}
}
If you want to display the button when starting the line:
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
var pos = richTextBox1.GetPositionFromCharIndex(richTextBox1.SelectionStart);
button2.Location = new Point(richTextBox1.Left - button2.Width - 2, pos.Y + richTextBox1.Top);
}
+2
source to share
You can get the position of the caret using the RichTextBox.GetPositionFromCharIndex
method:
int index = richTextBox1.SelectionStart;
Point caretPosition = richTextBox1.GetPositionFromCharIndex(index);
then you can use it to change the layout of the buttons:
int x = 280; //maybe something like richTextBox1.Location.X - 10;
int y = caretPosition.Y; //you might need to adjust this to button point of reference
button2.Location = new Point(x, y);
Handle an RichTextBox.SelectionChanged
event if you want to move the button when the caret is moved, not with a mouse click.
0
source to share