How check if key pressed in any textbox on winform

  • Thread starter Thread starter Woody Splawn
  • Start date Start date
W

Woody Splawn

I would like to be able to know if the user has pressed a key in any text
box on a winform or in other words, if he is editing a record. I would like
to know this as soon as he presses any key. I know that I can check for
keypress on a given field, but I don't want to do this for every field on
the form. Is there a way to determine what I want to know?
 
Set the KeyPreview property of the form to True. This makes all
keypress-related messages to be sent to the form first before sending it to
the actual text box or any other control. So, you can have all field
modification checks in the form's keypress events itself.


I would like to be able to know if the user has pressed a key in any text
box on a winform or in other words, if he is editing a record. I would like
to know this as soon as he presses any key. I know that I can check for
keypress on a given field, but I don't want to do this for every field on
the form. Is there a way to determine what I want to know?
 
Woody,

As alternative for shiva's answer you can make a keypress event for all your
textboxes on your form.

Assuming that the textboxes are not on another control as a panel (when that
is tell than I give an alternative code) you can do it like the code that I
made as sample bellow.

I hope this helps?

Cor

\\\just to try put some textboxes on a form and past this in the code
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
For Each ctr As Control In Me.Controls
If TypeOf ctr Is TextBox Then
AddHandler ctr.KeyPress, AddressOf TextBox_KeyPress
End If
Next
End Sub
Private Sub TextBox_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs)
MessageBox.Show("In textbox " & DirectCast(sender, TextBox).Name & _
" is key " & e.KeyChar.ToString & " pressed")
'this sentence is only to show how
End Sub

///
 
* "Shiva said:
Set the KeyPreview property of the form to True. This makes all
keypress-related messages to be sent to the form first before sending it to
the actual text box or any other control. So, you can have all field
modification checks in the form's keypress events itself.

ACK. In addition to that, you can use 'Me.ActiveControl' to determine
the control that has the input focus inside the form's keyboard events
event handlers.
 
Shiva,

This was very helpful. Thanks to you and Herfried and Cor for your
help.
 

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

Back
Top