【问题标题】:Does using SuppressKeyPress in a KeyDown event corrupt MaskedTextBoxes?在 KeyDown 事件中使用 SuppressKeyPress 是否会损坏 MaskedTextBoxes?
【发布时间】:2012-04-20 18:50:39
【问题描述】:

当用户按下MaskedTextBox 中的ENTER/RETURN 键时,我正在设置SuppressKeyPress = true,以防止通常发出的恼人的哔哔声。这很好用,但是当我清除我的表单时,MaskedTextBox 不再按预期运行。输入的第一个字符是幻影字符,在输入第二个字符后消失。

例子:

__.___
Set text = "0"
0_.___
User enters text
09.999
User presses ENTER
User presses Save & Next (this clears the form)
Reset text = "0"
0_.___
User enters first 9
09_.___
User enters second 9
0_.9__

如果用户在MaskedTextBox 之外使用 TABS 而不是按 ENTER,这可以正常工作(正确输入文本,没有任何奇怪的移位。)我能找到的唯一区别是我使用的是 SuppressKeyPress 并且Non-Public Members 中的 flagState 不同(当我不 SuppressKeyPress 时为 2052,当我在 SuppressKeyPress 时为 2048。)

有没有办法在不破坏 MaskedTextBox 的情况下防止 BEEP 或在 SuppressKeyPress 之后修复 MaskedTextBox 的方法(我已经尝试了大部分 MaskedTextBox 本身的方法:@ 987654333@、refresh等……)

这里是 MaskedTextBox 的定义和 KeyDown 方法:

// 
// aTextBox
// 
this.aTextBox.Location = new System.Drawing.Point(130, 65);
this.aTextBox.Mask = "##.###";
this.aTextBox.Name = "aTextBox";
this.aTextBox.Size = new System.Drawing.Size(50, 20);
this.aTextBox.TabIndex = 3;
this.aTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.general_KeyDown);
this.aTextBox.Leave += new System.EventHandler(this.validate);

general_KeyDown 看起来像这样:

private void general_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        e.Handled = true;
        e.SuppressKeyPress = true;
        SendKeys.Send("{TAB}");
    }
}

【问题讨论】:

    标签: c# .net winforms keydown maskedtextbox


    【解决方案1】:

    我无法复制,但我肯定会在参考源中看到它。 MaskTextBox 还在寻找 Keys.Enter 并在看到它时设置和内部标志,该标志会影响后续击键的键处理。您的代码可能会搞砸。

    通过覆盖 OnKeyDown 确保控件根本看不到击键。这需要继承您自己的控制权,如下所示:

    using System;
    using System.Windows.Forms;
    
    class MyMaskTextBox : MaskedTextBox {
    
        protected override void OnKeyDown(KeyEventArgs e) {
            if (e.KeyData == Keys.Enter) {
                e.Handled = e.SuppressKeyPress = true;
                this.Parent.GetNextControl(this, true).Select();
                return;
            }
            base.OnKeyDown(e);
        }
    }
    

    将代码粘贴到新类中并编译。从工具箱顶部删除新控件,替换旧控件。

    【讨论】:

    • 为了它的价值,我确实复制了它。 OP 的代码最终会在其下一次按键时插入一个空格 (Chr(32))。您的帖子使我免于发布可怕的骇人听闻的答案。 +1。
    • 这成功了!非常感谢你。使用 SendKeys.Key("{TAB}") 有什么缺点吗?简单地做 GetNextControl 很麻烦,因为表单上的一些控件是不活动的。
    • “活跃”没有多大意义。 GetNextControl 处理禁用的控件。使用你喜欢的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多