Help in keypress events

ljpv14

Active member
Joined
Nov 28, 2011
Messages
44
Programming Experience
3-5
HELP GUSY! I can't get my key press even to work. I want to have a key press event where when I press spacebar, I will perform some things.

Here is my code:
Private Sub gamePlay_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
If e.KeyChar = "32" Then
// perform code here
End If
End Sub

I search the internet saying that keycharis looking for the value of a certain key that is pressed. I got 32 for spacebar. My code is not working at all. Is there something wrong with my condition or approach? Or is there other ways to do that?

Thanks!
 
You want to do something when the user hits the spacebar, so e.KeyChar will be a space, yet you are comparing it to a String "32". Is that String a Char containing a space? It's not even a Char, so the system will have to implicitly convert it, which it does by taking the first character, so your code is actually testing whether the user entered a "3", not a space. If you want to check for a space then check for a space, not a "3". 32 is the ASCII code for the space character; it is not the space character itself.
 
If e.KeyChar = Chr(32) Then ~~~~~

I don't understand why so many people seem determined to unnecessarily work with ASCII codes. If you want a space Char then why not just use a space Char instead of converting an Integer to a Char? How many people would look at Chr(32) and wonder what character that actually was? Why make things more complex than they need to be?
VB.NET:
If e.KeyChar = " "c Then
 
Back
Top