Form.Acceptbutton已经设置了值,一般情况下,TextBox有焦点时,点击回车键就会触发Form.AcceptButton.Click事件。
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class FormDemo : Form
{
private TextBox textBox1;
private Button btnExe;
private Button btnAccept;
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.btnExe = new System.Windows.Forms.Button();
this.btnAccept = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(12, 12);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 21);
this.textBox1.TabIndex = 0;
//
// btnExe
//
this.btnExe.Location = new System.Drawing.Point(132, 12);
this.btnExe.Name = "btnExe";
this.btnExe.Size = new System.Drawing.Size(88, 23);
this.btnExe.TabIndex = 1;
this.btnExe.Text = "Execute";
this.btnExe.UseVisualStyleBackColor = true;
this.btnExe.Click += new System.EventHandler(this.btnExe_Click);
//
// btnAccept
//
this.btnAccept.Location = new System.Drawing.Point(132, 41);
this.btnAccept.Name = "btnAccept";
this.btnAccept.Size = new System.Drawing.Size(88, 23);
this.btnAccept.TabIndex = 2;
this.btnAccept.Text = "AcceptButton";
this.btnAccept.UseVisualStyleBackColor = true;
this.btnAccept.Click += new System.EventHandler(this.btnAccept_Click);
//
// FormDemo
//
this.AcceptButton = this.btnAccept;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.btnAccept);
this.Controls.Add(this.btnExe);
this.Controls.Add(this.textBox1);
this.Name = "FormDemo";
this.ResumeLayout(false);
this.PerformLayout();
}
public FormDemo()
{
InitializeComponent();
}
private void btnExe_Click(object sender, EventArgs e)
{
MessageBox.Show("Execute按钮点击");
}
private void btnAccept_Click(object sender, EventArgs e)
{
MessageBox.Show("Accept按钮点击");
}
}
}
运行结果如图
但是我们会有这样的需求,我们TextBox数据输入完毕,不想直接执行Form.AcceptButton.Click事件,怎么办?
我们可以利用TextBox.PreviewKeyDown事件。
public FormDemo()
{
InitializeComponent();
textBox1.PreviewKeyDown += textBox1_PreviewKeyDown;
}
void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnExe.PerformClick();
}
}
运行结果如图
奇怪两个按钮Click事件都执行了。
但是我们还想屏蔽AcceptButton的Click怎么办?
处理TextBox.PreviewKeyDown:
void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnExe.PerformClick();
e.IsInputKey = true;
}
}
运行结果如图
好的,我的第一个博文就这样吧。