在 RichTextBox 中选择一个词时如何显示面板?

How do I display a Panel when selecting a word in a RichTextBox?

当我 select 或双击 RichTextBox 中的一个词时,一个面板应该 出现在这个词的上方 (这个 panel 最初是隐藏的,并在单词突出显示时出现)。当我移除 selection 时,panel 应该消失。

private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
    if (richTextBox1.SelectedText.Length > 0)
       panel1.Visible = true;
    else
       panel1.Visible = false;
}

根据你的修改,你需要一个自定义控件来实现这个。 为此设置您的自定义位置,另一个问题可能是您的 Control(此处:buttonOverlay)的 z-index(优先级)。使用 buttonOverlay.BringToFront(),您会将其设置在前面。

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;
    }
}

要添加自定义 Control,请将以下代码添加到您的 Form 构造函数中:

this.buttonOverlay = new FormattingOverlay(this);
this.Controls.Add(this.buttonOverlay);
this.buttonOverlay.Visible = false;`

FormattingOverlay是继承自UserControl的class:

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;
    }
}

可以找到整个示例项目via this link.