如何使用同一按钮从粗体切换到常规字体样式
我在通过按钮选择的文本上应用 FontStyle Bold,但再次单击它时无法返回默认值 我希望当我第一次单击时,应用 FontStyle Bold,当我再次单击时,应用 FontStyle Regular。 有人可以帮我吗?
private void button3_Click(object sender, EventArgs e)
{
System.Drawing.Font bold = richTextBox1.SelectionFont;
System.Drawing.FontStyle noBold;
if (richTextBox1.SelectionFont.Bold == true)
{
noBold = FontStyle.Regular;
}
else
{
noBold = FontStyle.Bold;
}
richTextBox1.SelectionFont = new Font(richTextBox1.Font.FontFamily, richTextBox1.Font.Size, noBold);
}
I apply a FontStyle Bold on a text selected with a button but I can't go back to the default value when I click on it again
I would like that when I click the first time, the FontStyle Bold is applied and when I click again, the FontStyle Regular is applied.
Could someone please help me?
private void button3_Click(object sender, EventArgs e)
{
System.Drawing.Font bold = richTextBox1.SelectionFont;
System.Drawing.FontStyle noBold;
if (richTextBox1.SelectionFont.Bold == true)
{
noBold = FontStyle.Regular;
}
else
{
noBold = FontStyle.Bold;
}
richTextBox1.SelectionFont = new Font(richTextBox1.Font.FontFamily, richTextBox1.Font.Size, noBold);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的逻辑有问题。您正在检查是否有选定的文本,如果有,则将其设置为粗体,否则将其设置为不粗体,除非没有选定的文本,因此 nobold 没有效果。
您想要按照以下方式做更多事情(请注意,此示例代码是独立的。您应该在其他地方初始化字体对象。):
Your logic is faulty. You're checking if there is selected text and if there is, you make it bold, otherwise you make it not bold, except there is no selected text so nobold has no effect.
You want to do something more along the following lines (Note that this example code is self-contained. You should initialize your font objects elsewhere.):