WinForm 中的输入处理
阻止在文本框中使用某些输入键而不阻止特殊击键(例如 Ctrl-V/Ctrl- 的最佳方法是什么? C?
例如,只允许用户输入字符或数字的子集,例如 A 或 B 或 C,而不允许输入其他内容。
What is the best way to block certain input keys from being used in a TextBox with out blocking special keystrokes such as Ctrl-V/Ctrl-C?
For example, only allowing the user to enter a subset of characters or numerics such as A or B or C and nothing else.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果不允许使用该键,我将使用 keydown-event 并使用 e.cancel 来停止该键。 如果我想在多个地方执行此操作,那么我将创建一个继承文本框的用户控件,然后添加一个属性AllowedChars或DisallowedChars来为我处理它。 我有时会使用一些变体,其中一些允许货币格式和输入,一些用于时间编辑等等。
将其作为用户控件的好处是您可以添加它并将其添加到您自己的杀手文本框中。 ;)
I would use the keydown-event and use the e.cancel to stop the key if the key is not allowed. If I want to do it on multiple places then I would make a user control that inherits a textbox and then add a property AllowedChars or DisallowedChars that handle it for me. I have a couple of variants laying around that I use for time to time, some allowing money-formatting and input, some for time editing and so on.
The good thing to do it as a user control is that you can add to it and make it to your own killer-text-box. ;)
我使用了 winforms 的 Masked Textbox 控件。 这里有一个更长的解释。 本质上,它不允许输入与字段条件不匹配的输入。 如果您不希望人们输入除数字之外的任何内容,那么它就不允许他们输入除数字之外的任何内容。
I used the Masked Textbox control for winforms. There's a longer explanation about it here. Essentially, it disallows input that doesn't match the criteria for the field. If you didn't want people to type in anything but numbers, it simply would not allow them to type anything but numbers.
我通常是这样处理的。
这将只允许数字字符和退格键。 问题是在这种情况下您将不被允许使用控制键。 如果您想保留该功能,我会创建自己的文本框类。
This is how I handle this usually.
That will only allow numerical characters and the backspace. The problem is that you will not be allowed to use control keys in this case. I would create my own textbox class if you want to keep that functionality.
我发现唯一有效的解决方案是在 ProcessCmdKey 中对 Ctrl-V、Ctrl- 中的按键进行预检查C、Delete 或 Backspace,并使用正则表达式进一步验证是否不是 KeyPress 事件中的这些键之一。
这可能不是最好的方法,但它在我的情况下有效。
I found the only working solution ended being doing a pre-check of the keypress in the ProcessCmdKey for Ctrl-V,Ctrl-C, Delete or Backspace, and the doing a further validation if it was not one of these keys in the KeyPress event by using a regular expression.
This is probably not the best way but it worked in my circumstance.
您可以使用文本框的 TextChanged 事件。
You could use the TextChanged event for the textbox.