MsgBox problem

J

Jason

I have a form which is used to add items (stock symbols) to a list. On the form is a listbox, textbox, and a button. The list contains the current list of items, the textbox is for entering a new symbol, and the button does the actual adding. Before adding, I check to see if the is already in the list. If it is, I display a message using the MsgBox class and set the focus back to the textbox. To make data entry easier, I set a handler to the textbox's KeyUp event and listen for the Enter key. When pressed, I call the PerformClick event of the button.

Here is the problem. If I use the enter key to dismiss the MsgBox (when a duplicate symbol was entered) and the focus is set to the textbox, the KeyUp event goes off again with the KeyCode being enter. The only way to get out of the cycle is to use the mouse and click the MsgBox's Ok button.

Is there any way to clear the keyboard buffer after calling the MsgBox class?

You can reproduce the problem by following these directions (my code is VB.NET):

* Create new WIndows Forms project
* Put a TextBox control and a Button control on the form.
* Go into Code view and add the following code:

Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
If e.KeyCode = Keys.Enter Then Button1.PerformClick()
End Sub

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox("Hello")
TextBox1.Focus()
End Sub

- Thanks
 
G

Guest

Hi Jason,

Try with the following code remove KeyUp event of the textbox and use
KeyPress event...

try the following code...

Private Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Button1.Click
MsgBox("Hello")
TextBox1.Focus()
End Sub


Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Asc(e.KeyChar) = 13 Then
Button1_Click(Button1, New EventArgs)
End If
End Sub

with regards,

Sadha Sivam S,
Microsoft Community Star,
http://answerindotnet.blog.com
 
J

Jason

Thanks Sadha. Works great.

Follow up question is why? Why does the keyup event get passed back to the
textbox from the msgbox?

- Jason
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top