Csharp/C#教程:WinForm中的输入处理分享


WinForm中的输入处理

什么是阻止某些输入键在TextBox中使用而没有阻止特殊键击(如Ctrl-V / Ctrl-C)的最佳方法?

例如,仅允许用户输入字符或数字的子集,例如A或B或C,而不是其他任何内容。

如果不允许密钥,我会使用keydown事件并使用e.cancel来停止密钥。 如果我想在多个地方执行此操作,那么我将创建一个inheritance文本框的用户控件,然后添加一个属性AllowedChars或DisallowedChars来处理它。 我有几个变种,我不时使用,一些允许货币格式和输入,一些用于时间编辑等等。

作为用户控件执行此操作的好处是,您可以添加到它并使其成为您自己的杀手文本框。 ;)

我使用Masked Textbox控件来获取winforms。 这里有更长的解释。 从本质上讲,它不允许输入与字段标准不匹配。 如果你不希望人们输入除数字之外的任何东西,它根本不允许他们输入除数字之外的任何内容。

这就是我通常如何处理这个问题。

Regex regex = new Regex("[0-9]|b"); e.Handled = !(regex.IsMatch(e.KeyChar.ToString())); 

这只会允许数字字符和退格。 问题是在这种情况下您将不被允许使用控制键。 如果你想保留这个function,我会创建自己的文本框类。

我发现唯一可行的解​​决方案是在ProcessCmdKey中为Ctrl-V,Ctrl-C,Delete或Backspace预先检查按键,如果它不是KeyPress事件中的其中一个键,则进行进一步的validation通过使用正则表达式。

这可能不是最好的方式,但它在我的环境中起作用。

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { // check the key to see if it should be handled in the OnKeyPress method // the reasons for doing this check here is: // 1. The KeyDown event sees certain keypresses differently, eg NumKeypad 1 is seen as a lowercase A // 2. The KeyPress event cannot see Modifer keys so cannot see Ctrl-C,Ctrl-V etc. // The functionality of the ProcessCmdKey has not changed, it is simply doing a precheck before the // KeyPress event runs switch (keyData) { case Keys.V | Keys.Control : case Keys.C | Keys.Control : case Keys.X | Keys.Control : case Keys.Back : case Keys.Delete : this._handleKey = true; break; default: this._handleKey = false; break; } return base.ProcessCmdKey(ref msg, keyData); } protected override void OnKeyPress(KeyPressEventArgs e) { if (String.IsNullOrEmpty(this._ValidCharExpression)) { this._handleKey = true; } else if (!this._handleKey) { // this is the final check to see if the key should be handled // checks the key code against a validation expression and handles the key if it matches // the expression should be in the form of a Regular Expression character class // eg [0-9.-] would allow decimal numbers and negative, this does not enforce order, just a set of valid characters // [A-Za-z0-9-_@.] would be all the valid characters for an email this._handleKey = Regex.Match(e.KeyChar.ToString(), this._ValidCharExpression).Success; } if (this._handleKey) { base.OnKeyPress(e); this._handleKey = false; } else { e.Handled = true; } } 

您可以将TextChanged事件用于文本框。

上述就是C#学习教程:WinForm中的输入处理分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

  private void txtInput_TextChanged(object sender, EventArgs e) { if (txtInput.Text.ToUpper() == "A" || txtInput.Text.ToUpper() == "B") { //invalid entry logic here } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1043355.html

(0)
上一篇 2022年1月31日
下一篇 2022年1月31日

精彩推荐