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

烂漫一生 提交于 2019-12-11 07:28:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!