Catching KeyPress event

kokas

Member
Joined
Jul 21, 2005
Messages
12
Programming Experience
1-3
Hello

I have a windows form with the following code:

PublicClass Form1
Inherits System.Windows.Forms.Form

#
Region " Windows Form Designer generated code "
PublicSubNew()
MyBase.New()
InitializeComponent()
AddHandler Label1.KeyPress, AddressOf myKeyCounter
EndSub

ProtectedOverloadsOverridesSub Dispose(ByVal disposing AsBoolean)
If disposing Then
IfNot (components IsNothing) Then
components.Dispose()
EndIf
EndIf
MyBase.Dispose(disposing)
EndSub
#EndRegion

PrivatebackspacePressed AsLong = 0

PrivateSub myKeyCounter(ByVal sender AsObject, ByVal ex As KeyPressEventArgs)

SelectCase ex.KeyChar
Case ControlChars.Back
backspacePressed = backspacePressed + 1
EndSelect
Me.Label1.Text = backspacePressed & " backspaces pressed"
ex.Handled = True

EndSub
End
Class

Whenever i run the project though and click the backspace i see no changes to the label's text. How can i get this to work?

Thank you
 
Why so much confusions take a look at this:
VB.NET:
[size=2][color=#0000ff]Dim[/color][/size][size=2] bsPress [/size][size=2][color=#0000ff]As [/color][/size][size=2][color=#0000ff]Integer
 
[/color][/size][size=2][color=#0000ff]Private [/color][/size][size=2][color=#0000ff]Sub[/color][/size][size=2] Form1_KeyPress([/size][size=2][color=#0000ff]ByVal[/color][/size][size=2] sender [/size][size=2][color=#0000ff]As[/color][/size][size=2][color=#0000ff]Object[/color][/size][size=2], [/size][size=2][color=#0000ff]ByVal[/color][/size][size=2] e [/size][size=2][color=#0000ff]As[/color][/size][size=2] System.Windows.Forms.KeyPressEventArgs) [/size][size=2][color=#0000ff]Handles [/color][/size][size=2][color=#0000ff]MyBase[/color][/size][size=2].KeyPress
 
[/size][size=2][color=#0000ff]If[/color][/size][size=2] e.KeyChar = Chr(8) [/size][size=2][color=#0000ff]Then
 
[/color][/size][size=2]bsPress += 1
 
[/size][size=2][color=#0000ff]Me[/color][/size][size=2].Label1.Text = "BackSpace was pressed " & bsPress & " times so far"
 
[/size][size=2][color=#0000ff]End [/color][/size][size=2][color=#0000ff]If
 
[/color][/size][size=2][color=#0000ff]End [/color][/size][size=2][color=#0000ff]Sub[/color][/size]
[size=2][color=#0000ff]
[/color][/size]

HTH
Regards ;)
 
So my mistake was the delegate:

AddHandler Label1.KeyPress, AddressOf myKeyCounter

if i say

AddHandler Form1.KeyPress, AddressOf myKeyCounter
then it would be alright?
 
Yes it would be alright.
The reason is that a label can't recive the focus and therefore will never 'see' a keypress. The label only has a keypress event because it has the Control class as it's base. Therefore you need to use the KeyPress event of the form which can receive the focus. If there are other controls that can receive the focus (textboxs, buttons, ...) and one of those controls have the focus, the form will only receive the keypress if it's KeyPreview property is set to True.
 
Back
Top