Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 1 of 1
03-09-2011, 03:56 AM #1
VB.NET: KeyPress event seems to temporally reset one of my variables.
The problem is occurring in my Hangman project.
The only thing that is called when the game loads is:
Private CurrentPhraseIndex As Int32 = -1 Private Sub NewPhrase() CurrentPhraseIndex = GetRandomPhraseIndex() ' Get a random index ' If the number is within bounds If CurrentPhraseIndex > -1 And CurrentPhraseIndex < Level.Phrases.Count Then Label1.Text = Level.Phrases(CurrentPhraseIndex).Phrase ElseIf CurrentPhraseIndex = -2 Then EndOfGame() Else NewPhrase() End If End Sub
If the user clicks a letter on the form, an event occurs:
Private Sub ABox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ABox.Click Guess("A") End Sub
Private Sub HangmanForm_KeyPress(ByVal sender As System.Object, ByVal e As KeyEventArgs) Handles MyBase.KeyDown If GameFormOpen Then GameForm.GameForm_KeyPress(ChrW(e.KeyValue)) End If End Sub
In case relevant, GameForm is a child form within a container. I couldn't figure out how to add the event to the GameForm, so I put the event in the parent form and pass the key as a char to GameForm. I don't see how this would be the problem though.
Friend Sub GameForm_KeyPress(ByVal Key As Char) Guess(Key) End SubCode:
Private Sub Guess(ByVal Letter As Char) ' If the guess is a letter between a and z If CheckString(Letter.ToString.ToLower, "\b[a-z]", 1, 1) = True Then MsgBox(CurrentPhraseIndex) ' Display the value of the current phrase index ' If the index is within bounds If CurrentPhraseIndex > -1 And CurrentPhraseIndex < Level.Phrases.Count Then ' Search the string for the guessed letter For Each L In Level.Phrases(CurrentPhraseIndex).Phrase ' If the letter is found If L.ToString.ToLower = Letter.ToString.ToLower Then MsgBox(Letter) End If Next Else MsgBox("Index out of bounds!") End If End If End Sub
If I click the letter 'U,' the message box shows the phrase index as "3."
If I click the letter 'A,' the message box shows the phrase index as "3" and the letter as "A."
However, If I press the letter 'U' on the keyboard the message box shows the phrase index as "-1" and then the "Index out of bounds!" message is displayed. The exact same thing occurs no matter which button is pressed (Provided it passes the RegEx).
The part that really gets me is, after I press the letter 'U' and it shows me a "-1" as my index, if I then click the letter 'U,' it shows the correct Index as "3." What the monkey!?
I don't get it. Is this how the KeyPress and KeyDown events are supposed to work?
Last edited by bobleny; 03-09-2011 at 04:02 AM.--www.firemelt.net--
* No good deed goes unpunished.
* Cheer up, the worst has yet to come...