OK-Cancel Dialog: handling the 'Enter' key press

10,477

Solution 1

This is the way it is supposed to work. You should set the form's AcceptButton property to the OK button. It gets the fat border to indicate that it is the default button whose Click event automatically runs when the user presses Enter. If you set the button's DialogResult property to OK then it also assigns the DialogResult property automatically so that the dialog closes.

Don't fix it. If you want to debug it then set a break on the button's Click event handler. If you want to prevent it from closing then either reset the button's DialogResult property or set the form's DialogResult property back to None. Never use the KeyPressed event.

Solution 2

Check Properties of your form in Design View, ensure nothing is set for AcceptButton.

Solution 3

Answer 2 does the trick!

Nothing needs to be changed in the default OK_Button_Click sub

Just made a sub to handle change in input values - in my case ,it was a numeric input :

Private Sub SetKey_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SetKey.ValueChanged

        'Form1 do stuff

End Sub

I then added this code to shift the focus to the OK button. So, it is ready to accept Enter again and finish the dialog, if the user wants to finish - optional:

Private Sub frmMain_KeyDown(ByVal sender As System.Object, ByVal e As  System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress

    If e.KeyChar = Chr(Keys.Enter) Then OK_Button.Focus()

End Sub
Share:
10,477
Phonon
Author by

Phonon

Updated on June 05, 2022

Comments

  • Phonon
    Phonon almost 2 years

    I'm building a Dialog in Winforms. It's got the two OK and Cancel buttons that are there when you create it, which is what I want. In this dialog I also have a TextBox and a Sub (coding in VB.NET) that handles its KeyPress event. I need stuff to happen when the 'Enter' key is pressed.

    Now, I've done such KeyPress handling times and times again. This situation, however, is different, because as soon as 'Enter' key is pressed, the dialog automatically assumes you're pressing the 'OK' button, returns a result and closes. In both the Designer and the actual form when running the application, the OK button is highlight, which means is has some kind of a focus (for the lack of a better term) at all times. How can I disable this feature of a dialog? When I debug my code, pressing enter does not even get to the sub handling the KeyPress event. It simply closes the dialog and returns the result, therefore I can't really step through the code and see what happens behind the scenes.

    To restate the question, how can I disable this functionality?

    Cheers! = )