根據您的更改,您需要一個自定義控件來實現此目的。 爲此設置您的自定義位置,另一個問題可能是您的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.
來源
2017-06-01 17:37:32
jAC
那麼問題是什麼? – Icemanind
如何使面板出現在所選單詞的上方? – Aino
您可能需要檢查[此問題](https://stackoverflow.com/q/11389601/3775798),瞭解如何獲取所選單詞的位置信息以定位面板。 –