好的,这件事情正在困扰着我,我就是想不出问题出在哪里...
我创建了两个表单。第一个表单只有一个简单的按钮,当点击该按钮时,会像下面这样打开另一个对话框:
using (Form2 f = new Form2())
{
if (f.ShowDialog() != DialogResult.OK)
MessageBox.Show("Not 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之外,我没有做其他任何事情。为什么它不起作用?
DialogResult
之外,我还需要将我的窗体的显示方法从.Show()
更改为.ShowDialog()
,以使 ESC 和 ENTER 键正常工作。 - Der_Reparator