gpt4 book ai didi

c# - 使用 C# .net 防止 RichTextBox 中的退格键

转载 作者:行者123 更新时间:2023-12-02 21:22:25 25 4
gpt4 key购买 nike

我正在为这件事揪心。非常简单的Windows窗体程序。我有一个富文本框,我想防止退格键在富文本框中执行任何操作。这是我的代码

private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back)
{
e.handled = true;
}
}

如果我在 e.handled 处放置一个断点并输入一个退格键,它确实会中断。然而,退格键仍然可以到达富文本框。所以我见过使用 PreviewKeyDown 的示例,但是这些示例都不起作用!我试过了

void richTextBox1.PreviewKeyDown(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}

但是 KeyPressEventArgs 无效!如果我使用 Forms 提供的 PreviewKeyDownEventArgs,并且没有可用的 e.Handles。那么如何做到这一点呢?

谢谢

最佳答案

使用 KeyDown 事件取消退格键按下。

private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
e.Handled = true;
}
}

有关 KeyPress 事件的 MSDN 页面有以下评论:

Some controls will process certain key strokes on KeyDown. For example, RichTextBox processes the Enter key before KeyPress is called. In such cases, you cannot cancel the KeyPress event, and must cancel the key stroke from KeyDown instead.

关于c# - 使用 C# .net 防止 RichTextBox 中的退格键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26679190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com