我正在使用RichTextBox
为自己制作一个Notes应用程序,我在使用Font“Styling”时遇到了一些问题。我绑定Ctrl + I将所选文本设置为斜体,这是有效的。但出于某种原因,每当我这样做时,它会添加一个标签,删除所有选定的文本。通过添加e.SuppressKeyPress = true,我可以找到与该问题有关的唯一案例。但那也不适合我。
private void txbMain_KeyUp(object sender, KeyEventArgs e)
{
if((e.KeyCode==Keys.B && e.Modifiers == Keys.Control) || (e.KeyCode==Keys.F && e.Modifiers==(Keys.Control | Keys.Shift)))
{
FontHelper.Bold(this);
}
else if(e.KeyCode==Keys.I && e.Modifiers == Keys.Control)
{
if (txbMain.SelectionFont != null)
{
e.SuppressKeyPress = true;
System.Drawing.Font currentFont = txbMain.SelectionFont;
System.Drawing.FontStyle newFontStyle;
if (txbMain.SelectionFont.Italic == true)
{
newFontStyle = FontStyle.Regular;
}
else
{
newFontStyle = FontStyle.Italic;
}
txbMain.SelectionFont = new Font(
currentFont.FontFamily,
currentFont.Size,
newFontStyle
);
}
}
}
CTRL + I组合似乎是richtextbox的默认功能,可以输入选项卡。即使您在richtextbox上没有任何代码或事件,您的文本也将被替换。所以问题是,在此默认功能之后,您的事件会被触发,并且在代码到达文本格式后文本已被删除。
最简单的解决方案是使用KeyDown事件而不是KeyUp。