问题
When I select or double-click on a word in the RichTextBox, a panel should appear above this word (This panel is initially hidden and appears when the word is highlighted). When I remove the selection, the panel should disappear.
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
if (richTextBox1.SelectedText.Length > 0)
panel1.Visible = true;
else
panel1.Visible = false;
}
回答1:
According to your changes, you need a custom control to achieve this.
Set your custom location for that, another problem might be the z-index (priority) of your Control (here: buttonOverlay). With buttonOverlay.BringToFront(), you'll set it to the front.
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
if (richTextBox1.SelectedText.Length > 0)
{
Point relativePoint = rTxtBxSelectionTester.GetPositionFromCharIndex(rTxtBxSelectionTester.SelectionStart);
int txtBsPosX = relativePoint.X + rTxtBxSelectionTester.Location.X;
int txtBxPosY = relativePoint.Y + rTxtBxSelectionTester.Location.Y - this.buttonOverlay.Size.Height;
relativePoint = new Point(txtBsPosX, txtBxPosY);
this.buttonOverlay.Location = relativePoint;
this.buttonOverlay.Visible = true;
this.buttonOverlay.BringToFront();
}
else
{
this.buttonOverlay.Visible = false;
}
}
To add the custom Control add the following code to your Form constructor:
this.buttonOverlay = new FormattingOverlay(this);
this.Controls.Add(this.buttonOverlay);
this.buttonOverlay.Visible = false;`
The FormattingOverlayis a class that inherits from UserControl:
public partial class FormattingOverlay : UserControl
{
public FormattingOverlay(Form1 mainForm)
{
this.mainForm = mainForm;
InitializeComponent();
}
private void btnBold_Click(object sender, EventArgs e)
{
RichTextBox rTxtBx = mainForm.rTxtBxSelectionTester;
rTxtBx.SelectionFont = new Font(rTxtBx.Font, FontStyle.Bold);
rTxtBx.SelectionStart = rTxtBx.SelectionStart + rTxtBx.SelectionLength;
rTxtBx.SelectionLength = 0;
rTxtBx.SelectionFont = rTxtBx.Font;
}
}
The whole sample project can be found via this link.
来源:https://stackoverflow.com/questions/44313656/how-do-i-display-a-panel-when-selecting-a-word-in-a-richtextbox