在 RichTextBox 中选择单词时如何显示面板? [英] How do I display a Panel when selecting a word in a RichTextBox?
问题描述
当我在 RichTextBox
中选择或双击一个词时,一个面板应该出现在这个词上方(这个 panel
最初是隐藏并在突出显示单词时出现).当我删除选择时,panel
应该消失.
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;
}
推荐答案
根据您的更改,您需要一个自定义控件来实现此目的.为此设置您的自定义位置,另一个问题可能是您的 Control
(此处:buttonOverlay
)的 z-index
(优先级).使用buttonOverlay.BringToFront()
,您将把它设置在最前面.
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;
}
}
要添加自定义 Control
,请将以下代码添加到您的 Form
构造函数中:
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;`
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;
}
}
可以通过此链接找到整个示例项目.
这篇关于在 RichTextBox 中选择单词时如何显示面板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!