【问题标题】:How do I display a Panel when selecting a word in a RichTextBox?在 RichTextBox 中选择单词时如何显示面板?
【发布时间】:2017-06-01 17:23:58
【问题描述】:

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

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

【问题讨论】:

  • 那么问题是什么?
  • 如何让面板出现在选中的单词上方?
  • 您可能需要查看this question,了解如何获取选定单词的位置信息以定位您的面板。

标签: c# winforms richtextbox


【解决方案1】:

根据您的更改,您需要一个自定义控件来实现这一点。 为此设置您的自定义位置,另一个问题可能是您的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的类:

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.

【讨论】:

  • 这个面板上不应该有文字。我需要在这个面板上有按钮。
  • 在这个面板中,文本格式按钮应该位于。如果用户选择了一个词,那么这个面板就会出现,其中包含所选词或行的编辑按钮。
  • 我对代码做了一些修改,看了一下,还新建了一个示例项目。
  • 看起来不错,但是上面的面板怎么抬高呢?面板应位于所选单词的上方。
  • int txtBsPosX = relativePoint.X + rTxtBxSelectionTester.Location.X; int txtBxPosY = relativePoint.Y + rTxtBxSelectionTester.Location.Y - buttonOverlay.Size.Height; relativePoint = new Point(txtBsPosX, txtBxPosY);
猜你喜欢
  • 2017-11-19
  • 1970-01-01
  • 2015-12-12
  • 2014-03-08
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 1970-01-01
相关资源
最近更新 更多