2011-03-09 136 views
0

我有一个特殊的TextBox应该在Enter上验证。停止传播键盘事件到父窗体

在此验证上,如果已经定义了AcceptButton,则表单应该被提交。

在下面的代码我有两个文本框:一个正常的,和另外一个 - myTextBox - 用于验证本身上输入辅助(DoubleClick的形式一次看到它):

public partial class Form1 : Form 
{ 
    private TextBox TextBox1; 
    private MyTextBox MyTextBox1; 
    private Button OKButton; 
    public Form1() 
    { 
     InitializeComponent(); 

     TextBox1 = new TextBox(); 
     TextBox1.Parent = this; 
     TextBox1.Location = new Point(0, 50); 

     MyTextBox1 = new MyTextBox(); 
     MyTextBox1.Parent = this; 
     MyTextBox1.Location = new Point(0, 100); 
     MyTextBox1.Visible = false; 

     OKButton = new Button(); 
     OKButton.Parent = this; 
     OKButton.Location = new Point(0, 125); 
     OKButton.Click += new EventHandler(OKButton_Click); 

     this.AcceptButton = OKButton; 
    } 

    void OKButton_Click(object sender, EventArgs e) 
    { 
     if (MyTextBox1.Visible) 
      return; 
     Console.WriteLine("!!! OKButton_Click !!!"); 
    } 

    protected override void OnMouseDoubleClick(MouseEventArgs e) 
    { 
     MyTextBox1.Visible = true; 
     base.OnMouseDoubleClick(e); 
    } 
} 

public class MyTextBox : TextBox 
{ 
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
    { 
     if (keyData == Keys.Enter) 
     { 
      Console.WriteLine("!!! MyTextBox_Validation !!!"); 
      this.Visible = false; 
     } 
     return base.ProcessCmdKey(ref msg, keyData); 
    } 
} 

“验证”的事实由myTextBox知名度反映,但是这并没有帮助,因为在OKBUtton_Click myTextBox1已不可见...

enter image description here

理想的情况下,myTextBox验证后,我想阻止Enter键的Mes在父窗体上的鼠尾草繁殖。可能吗?如果不是,我应该如何验证MyTextBox而不验证表单?

回答

3

我希望我能正确理解你的问题。如果处理事件,您是否尝试在ProcessCmdKey覆盖中返回TRUE?返回true告诉事件系统该事件已被消耗并阻止进一步处理例如:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { 
    if (keyData == Keys.Enter) { 
     Console.WriteLine("!!! MyTextBox_Validation !!!"); 
     this.Visible = false; 
     return true; 
    } 
    return base.ProcessCmdKey(ref msg, keyData); 
} 
+0

很好的说法,托尼 – serhio 2011-03-09 14:04:13