Form keypress, detecting

bfsog

Well-known member
Joined
Apr 21, 2005
Messages
50
Location
UK
Programming Experience
5-10
I have a textbox, and if the user is focusing on it, and caps lock key is on (or true) a label is displayed.

However, what i want is for even if the user is not focusing the textbox, and they press the caps lock key, for the label to be displayed, and vice versa.

Thanks guys.
 
I've never used it myself, but I believe that if you set the KeyPreview property of the Form to True, the Form will receive all keyboard related events before the focused Control does.
 
KeyPress event

I used the keypress event to make the enter key behave like a tab key on a textbox. It is more data entry friendly for entering from the number pad. Perhaps this code will give you some ideas or steer you in the right direction. I did have to set KeyPreview = True.

Private Sub Form1_KeyPress _
(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles MyBase.KeyPress

If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Enter) Then
If TypeOf Me.ActiveControl Is TextBox Then
Dim tb As TextBox = DirectCast(Me.ActiveControl, TextBox)
If tb.Multiline AndAlso tb.AcceptsReturn Then
e.Handled = False
Exit Sub
End If
End If
e.Handled = True
Dim oform As Form = Me.FindForm
oform.SelectNextControl(oform.ActiveControl, True, True, True, True)
oform.ActiveControl.Focus()
End If
End Sub

hope this helps...
 
VB.NET:
Private Sub Form1_KeyDown (...) Handles MyBase.KeyDown
  If e.KeyCode = Keys.CapsLock Then
	lblCapsLock.Visible = Not lblCapsLock.Visible
  End If
End Sub

Private Sub Form1_KeyPress (...) Handles MyBase.KeyPress
  If Asc(e.KeyChar) = Keys.Enter Then
	If TypeOf Me.ActiveControl Is TextBox Then
	  Dim tb As TextBox = DirectCast(Me.ActiveControl, TextBox)
	  If tb.Multiline = True And tb.AcceptsReturn = True Then
		e.Handled = False
	  Else
		e.Handled = True
		Dim oform As Form = Me.FindForm
		oform.SelectNextControl(oform.ActiveControl, True, True, True, True)
		oform.ActiveControl.Focus()
	  End If
	End If
  End If
End Sub

i'm assuming that the label you want to be displayed when the capslock is on is named lblCapsLock
 
Last edited:
Back
Top