2011-03-09 103 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