VB 2008 Express (KeyPress help needed)

chupalo17

New member
Joined
Nov 20, 2009
Messages
2
Programming Experience
Beginner
Beginner here and need a little guidance. I've been banging my head against the wall trying to figure out a simple keypress handling event.

I have the code working fine after hunting for a couple of days on the net but have a problem getting rid of the obnoxious bong that comes along with hitting the ENTER key.

I've attempted some solutions on the web about changing the KeyAscii to 0 but under that method I cannot even get the program to recognize the key is even being pressed. If someone can point me in the right direction I would really appreciate it.

The code I have so far is as follows and I'm just trying to get rid of the audible bong.

VB.NET:
Expand Collapse Copy
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As  System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            Call Button1_Click(sender, e)
        End If
    End Sub
 
Last edited:
First up, please post in the most appropriate forum for the topic. VS.NET General is for general IDE questions. Thread moved.

As for the question, note that the KeyDown and KeyUp events relate to keys on the keyboard while the KeyPress event relates to input characters. For instance, Shift and A are two keyboard keys so they would raise two KeyDown and KeyUp events, but there would only be one KeyPress event for the upper case "A". You're looking for the Enter key, so you should be handling the KeyDown event and then comparing e.KeyCode or e.KeyData to Keys.Enter.

Also, don't call event handlers directly like that. If you want to "click" a Button in code then just call its PerformClick method.

Finally, you don't actually need code to get a Button to respond to the Enter key. You can just assign the Button to the form's AcceptButton property and it will be automatically "clicked" when you hit Enter, assuming the current active control doesn't consume the key for another purpose. The CancelButton property does the same thing for the Escape key.
 
I apologize for being in the wrong forum. Sometimes there are just so many forums to choose from.

Anyway, I truly appreciate your help. The AcceptButton property was exactly what I needed. I can't tell you how many postings I've read this week. I just couldn't believe it was this hard to find the solution I needed.

Truly, thanks again.
 
Back
Top