从 FontStyle 中减去标志(切换 FontStyles)[C#]

发布于 2024-10-03 00:23:36 字数 850 浏览 0 评论 0原文

我有一个小问题。我有 1 个 RichTextBox 和 2 个按钮。

我有两个按钮“切换粗体 FStyle”和“切换斜体 FStyle”。

我想切换 FontStyles 而不影响其他 FontStyles。我希望你能理解我。

下面的代码在组合 FontStyles 时有效,但在分离/减去 FontStyles 时不起作用。

private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font, (richTextBox1.SelectionFont.Bold == false ? richTextBox1.SelectionFont.Style | FontStyle.Bold : richTextBox1.SelectionFont.Style));
}

private void button2_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font, (richTextBox1.SelectionFont.Italic == false ? richTextBox1.SelectionFont.Style | FontStyle.Italic : richTextBox1.SelectionFont.Style));
}
  1. 我将选定的文本设为粗体
  2. 我将选定的文本设为斜体
  3. 我想在粗体仍处于活动状态(或相反)时删除斜体

I have a little problem. I have one 1 RichTextBox and 2 Buttons.

I have that 2 buttons for "toggle Bold FStyle" and "toggle Italic FStyle".

I want to toggle FontStyles without affecting other FontStyles. I hope you understand me.

Below code works when combining FontStyles but is not working when seperating/substracting FontStyles.

private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font, (richTextBox1.SelectionFont.Bold == false ? richTextBox1.SelectionFont.Style | FontStyle.Bold : richTextBox1.SelectionFont.Style));
}

private void button2_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font, (richTextBox1.SelectionFont.Italic == false ? richTextBox1.SelectionFont.Style | FontStyle.Italic : richTextBox1.SelectionFont.Style));
}
  1. I make selected text Bold
  2. I make selected text Italic
  3. I want to remove Italic while Bold is still active (or opposite)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深陷 2024-10-10 00:23:36

最简单的方法是使用按位异或 (^),它只是切换值:

private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font,
        richTextBox1.SelectionFont.Style ^ FontStyle.Bold);
}

private void button2_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font,
        richTextBox1.SelectionFont.Style ^ FontStyle.Italic);
}

The easiest way is to use bitwise XOR (^), which just toggles the value:

private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font,
        richTextBox1.SelectionFont.Style ^ FontStyle.Bold);
}

private void button2_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font,
        richTextBox1.SelectionFont.Style ^ FontStyle.Italic);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文