2009-01-28 15 views
34

好吧,這是竊聽我,我只是不知道有什麼問題...WinForms AcceptButton不工作?

我做了兩種形式。第一種形式只是上有一個簡單的按鈕,這將打開其他的對話,像這樣:

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

第二,這是Form2,上有兩個按鈕。我所做的一切就是將AcceptButton的形式設置爲一個,將CancelButton的形式設置爲另一個。在我的腦海裏,這是完成這項工作所需要的一切。但是當我運行它時,我點擊打開Form2的按鈕。我現在可以點擊一個設置爲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); 
} 

我做別的,只是添加這兩個按鈕,並設置的AcceptButton和CancelButton。爲什麼它不起作用?

回答

52

只需設置的AcceptButton/CancelButton設置DialogResult是不夠的。這只是告訴哪個按鈕應該在上輸入/Esc。您必須在Button處理程序中設置DialogResult。

+13

奇怪的是,設置CancelButton實際上將該按鈕的DialogResult設置爲取消,但AcceptButton對該按鈕不起作用。 – Carl 2009-01-28 15:11:30

+0

Aaaaah。謝謝!!這reeaally竊聽我,哈哈。你絕對正確。取消按鈕的dialogresult設置爲取消,但另一個沒有。沒有想到那個對話結果屬性...哦。再次感謝您:) – Svish 2009-01-28 15:39:26

47

嘗試button1

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

我喜歡你的答案比接受的答案更好,因爲你明確指定了需要完成的工作。 (除了混淆按鈕1與按鈕2之外:-) – RenniePet 2012-05-22 23:02:13

0

我曾與的AcceptButton的問題沒有工作,而DialogResult的建議是修復的一部分,我有2米是需要改變其他的東西:

  1. 我的按鈕是不可見的 - 故意,因爲我想當通過掃描條形碼「回車」回車時停止「回車」。
  2. 按鈕在裏面的容器有所不同。我必須把它放在同一個容器中,在我的情況下是一個Forms.Panel,作爲試圖訪問它的文本框。我不知道爲什麼這會有所作爲,但它確實如此。

我希望這可以幫助別人。

0

您需要將窗體的KeyPreview屬性設置爲True,默認值爲False。請記住,如果將焦點設置爲任何其他按鈕而不是AcceptButton,則Enter鍵將執行此按鈕

相關問題