WinForms AcceptButton无法正常工作?

问题描述 投票:36回答:5

好吧,这让我烦恼,我只是想不通有什么问题......

我有两种形式。第一个表单只有一个简单的按钮,它打开另一个作为对话框,如下所示:

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。为什么不起作用?

c# winforms modal-dialog
5个回答
54
投票

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


50
投票

尝试在DialogResult上设置button1

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


1
投票

我有一个问题,AcceptButton不工作,虽然DialogResult建议是修复的一部分,我有另外两件事需要改变:

  1. 我的按钮不可见 - 故意是因为我想通过扫描条形码来“按下”回车时停止“叮”。
  2. 按钮所在的容器有所不同。我必须将它放在同一个容器中,在我的例子中是一个Forms.Panel,作为试图访问它的文本框。我不确定为什么这会有所作为,但确实如此。

我希望这可以帮助别人。


0
投票

您需要将表单的KeyPreview属性设置为True,默认值为False。请记住,如果将焦点设置为任何其他按钮而不是AcceptButton,则Enter键将执行此按钮

© www.soinside.com 2019 - 2024. All rights reserved.