gpt4 book ai didi

c# - WinForms AcceptButton 不工作?

转载 作者:IT王子 更新时间:2023-10-29 03:59:22 25 4
gpt4 key购买 nike

好吧,这让我很烦,我就是想不通哪里出了问题...

我做了两个表格。第一个表单只有一个简单的按钮,它可以像这样打开另一个对话框:

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

第二个是 Form2,上面有两个按钮。我所做的只是将表单 AcceptButton 设置为一个,将 CancelButton 设置为另一个。在我看来,这就是完成这项工作所需的全部。但是当我运行它时,我单击打开 Form2 的按钮。我现在可以单击设置为 CancelButton 的按钮,然后我会看到“Not 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 之外,我什么也没做。为什么它不起作用?

最佳答案

仅仅设置AcceptButton/CancelButton 是不够的。这只是告诉应该在 Enter/Esc 上调用哪个按钮。您必须设置按钮的 DialogResult 属性。

关于c# - WinForms AcceptButton 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/487920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com