WinForms AcceptButton不起作用?
WinForms AcceptButton不起作用?
好的,这个问题困扰着我,我就是找不出问题在哪里...
我创建了两个窗体。第一个窗体上只有一个简单的按钮,点击该按钮会将另一个窗体作为对话框打开,代码如下:
using (Form2 f = new Form2()) { if (f.ShowDialog() != DialogResult.OK) MessageBox.Show("不OK"); else MessageBox.Show("OK"); }
第二个窗体就是那个Form2
,它上面有两个按钮。我所做的只是将窗体的AcceptButton设置为一个按钮,CancelButton设置为另一个按钮。在我的脑海中,这应该足够让它工作了。但是,当我运行它时,我点击打开Form2的按钮,现在我可以点击设置为CancelButton的按钮,得到“不OK”的消息框。但是当我点击设置为AcceptButton的按钮时,什么都不会发生?
Form2的InitializeComponent代码如下:
private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(211, 13); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; // // button2 // this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.button2.Location = new System.Drawing.Point(130, 13); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(75, 23); this.button2.TabIndex = 1; this.button2.Text = "button2"; this.button2.UseVisualStyleBackColor = true; // // Form2 // this.AcceptButton = this.button1; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.button2; this.ClientSize = new System.Drawing.Size(298, 59); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Name = "Form2"; this.Text = "Form2"; this.Load += new System.EventHandler(this.Form2_Load); this.ResumeLayout(false); }
除了添加这两个按钮并设置AcceptButton和CancelButton外,我什么都没做。为什么它不起作用呢?
问题:WinForms的AcceptButton不起作用?
原因:仅仅设置AcceptButton/CancelButton是不够的。这只是告诉系统哪个按钮应该在按下Enter/Esc键时被调用。您还需要设置按钮的DialogResult属性。
解决方法:设置CancelButton实际上会将该按钮的DialogResult设置为Cancel,但AcceptButton并不会对该按钮执行相同的操作。所以需要手动设置AcceptButton的DialogResult属性。
代码示例:
// 设置AcceptButton button1.AcceptButton = true; // 设置DialogResult button1.DialogResult = DialogResult.OK;
此外,除了设置按钮的DialogResult属性,还需要将Form的显示方法从.Show()更改为.ShowDialog(),以便ESC和ENTER键正常工作。
代码示例:
// 使用.ShowDialog()方法显示Form form1.ShowDialog();