WinForms AcceptButton不工作?

好吧,这是在烦我,我只是不知道有什么问题…

我做了两种forms。 第一种forms只是一个简单的button,打开另一个像对话框一样:

using (Form2 f = new Form2()) { if (f.ShowDialog() != DialogResult.OK) MessageBox.Show("Not OK"); else MessageBox.Show("OK"); } 

第二个是Form2 ,它有两个button。 我所做的就是将AcceptButton的forms设置为一个,将CancelButton的forms设置为另一个。 在我的脑海里,这是完成这项工作所需要的一切。 但是当我运行它时,我点击打开Form2的button。 我现在可以点击一个设置为CancelButton,我得到“不正确”的消息框。 但是当我点击一个设置为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); } 

除了添加这两个button,我什么都没做,并设置AcceptButton和CancelButton。 为什么不起作用?

只要设置AcceptButton / CancelButton是不够的。 这只是告诉在Enter / Esc上应该调用哪个button。 您必须在Button处理程序中设置DialogResult。

尝试在button1上设置DialogResult

 this.button1.DialogResult = System.Windows.Forms.DialogResult.OK; 

绝对尝试教程如何在Winform中自定义对话框轻松地应用AcceptButton和CancelButton

我有一个AcceptButton不能正常工作的问题,而DialogResultbuild议是修复的一部分,我还有其他两件事情需要改变:

  1. 我的button不可见 – 特意因为我想通过扫描条形码“回车”来停止“回车”。
  2. button在里面的容器有所不同。 我必须在同一个容器,在我的情况下,一个Forms.Panel,作为正在尝试访问它的文本框。 我不知道为什么这会有所作为,但它做到了。

我希望这可以帮助别人。