Question

I have a problem with the accept-button inside a Windows Form. The Form contains two buttons (OK and Cancel). Inside the Form I set the properties of the cancel and accept - Button to the specific buttons. In addition to that I also created a simple Click - Event for both buttons. But when I run the application and press enter the breakpoint inside my Click-Method doesn't get hit und nothing happens. On the other hand, the cancel button just works fine. Even if I switch the accept- and cancelbutton the acceptbutton doesn't work and the application seems to ignore the enter-input. I have looked up the designer several times but couldn't find anything which could lead to this behaviour. The Click Event itself also works fine when clicking the button, it's just about the enter-input. So my question is: Does someone have a clue where this strange behaviour comes from?

Designer:
// 
// SearchForm
// 
this.AcceptButton = this.BtnSearch;
this.CancelButton = this.BtnCancel;
//
//BtnSearch
//
this.BtnSearch.DialogResult = System.Windows.Forms.DialogResult.OK;
this.BtnSearch.Location = new System.Drawing.Point(12, 60);
this.BtnSearch.Name = "BtnSearch";
this.BtnSearch.Size = new System.Drawing.Size(75, 23);
this.BtnSearch.TabIndex = 1;
this.BtnSearch.Text = "Search";
this.BtnSearch.Click += new System.EventHandler(this.BtnSearch_Click);    
// 
// BtnCancel
// 
this.BtnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.BtnCancel.Location = new System.Drawing.Point(108, 60);
this.BtnCancel.Name = "BtnCancel";
this.BtnCancel.Size = new System.Drawing.Size(75, 23);
this.BtnCancel.TabIndex = 5;
this.BtnCancel.Text = "Cancel";
this.BtnCancel.Click += new System.EventHandler(this.BtnCancel_Click);




Form:
private void BtnCancel_Click(object sender, EventArgs e)
{
   this.Close();
}

private void BtnSearch_Click(object sender, EventArgs e)
{
   //DoStuff
}
Was it helpful?

Solution

Check what control has the focus when you press Enter. If that's a button then the key stroke is going to click that button, not the AcceptButton.

That makes AcceptButton a pretty lame property for dialogs that have more than an OK and Cancel key. Favor doing it like this instead:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
    if (keyData == Keys.Enter) {
        btnSearch.PerformClick();
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

OTHER TIPS

Are you showing the form as modal dialog? I think accept and cancel buttons only works for modal dialog. The example given in MSDN article shows modal dialog.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top