在类(你的窗体)的构造方法中加入以下代码进行事件绑定foreach (Control c in this.Controls) { c.KeyPress += new System.Windows.Forms.KeyPressEventHandler(test); }在类(你的窗体)里加入如下方法 private void test(object sender, KeyPressEventArgs e) { if (e.KeyChar == 13) { foreach (Control c in this.Controls) { if (c is System.Windows.Forms.TextBox) { SendKeys.Send("{Tab}"); } } } }
重写ProcessCmdKey事件,拦截回车键,集中处理,防止活动控件第二次响应.protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) { if (msg.WParam.ToInt32() == (int)Keys.Enter) { switch (ActiveControl.Name) { case "button1": MessageBox.Show(button1.Text); return true; case "textBox1": MessageBox.Show(textBox1.Text); return true; case "textBox2": case "textBox3": return true; } // 不符合条件的,不管它,正常执行 } return base.ProcessCmdKey(ref msg, keyData); }
{
c.KeyPress += new System.Windows.Forms.KeyPressEventHandler(test);
}在类(你的窗体)里加入如下方法
private void test(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
foreach (Control c in this.Controls)
{
if (c is System.Windows.Forms.TextBox)
{
SendKeys.Send("{Tab}");
}
}
}
}
{
if (msg.WParam.ToInt32() == (int)Keys.Enter)
{
switch (ActiveControl.Name)
{
case "button1": MessageBox.Show(button1.Text); return true;
case "textBox1": MessageBox.Show(textBox1.Text); return true;
case "textBox2":
case "textBox3":
return true;
}
// 不符合条件的,不管它,正常执行
}
return base.ProcessCmdKey(ref msg, keyData);
}
加到你的Form类中,与Form1_Load(...)是同级成员.
{
if(keyData == Keys.Enter )
{
SendKeys.Send("{Tab}");
return true;
}
return base.ProcessCmdKey (ref msg, keyData);
} 或
private void frmLogin_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter )
{
SendKeys.Send("{Tab}");
}
}