woutervk woutervk - 3 months ago 13
Vb.net Question

Setting focus on form

Currently I am building a small calculator.
You can use buttons to set the numbers used in the calculation. Now I'm working on a keyboard input. I have the following code, but when the application is launched, I can't type anything.
I think it's broken because the focus is not set on the form itself, but I don't know how to set this. Can anybody help me?

Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
Select Case e.KeyChar
Case Convert.ToChar(48)
Cijfer(Cijfer:="0")
Case Convert.ToChar(49)
Cijfer(Cijfer:="1")
Case Convert.ToChar(50)
Cijfer(Cijfer:="2")
Case Convert.ToChar(51)
Cijfer(Cijfer:="3")
Case Convert.ToChar(52)
Cijfer(Cijfer:="4")
Case Convert.ToChar(53)
Cijfer(Cijfer:="5")
Case Convert.ToChar(54)
Cijfer(Cijfer:="6")
Case Convert.ToChar(55)
Cijfer(Cijfer:="7")
Case Convert.ToChar(56)
Cijfer(Cijfer:="8")
Case Convert.ToChar(57)
Cijfer(Cijfer:="9")
Case Convert.ToChar(44)
TextOpNul()
If Controleren() = True Then
Else
If Not (TextBox1.Text.Contains(",")) Then
TextBox1.Text += ","
End If
End If
Case Convert.ToChar(47)
If Controleren() = True Then
Else
TekenKnop(TekenNr:=1)
End If
Case Convert.ToChar(42)
If Controleren() = True Then
Else
TekenKnop(TekenNr:=2)
End If
Case Convert.ToChar(45)
If Controleren() = True Then
Else
TekenKnop(TekenNr:=3)
End If
Case Convert.ToChar(43)
If Controleren() = True Then
Else
TekenKnop(TekenNr:=4)
End If
Case Convert.ToChar(13)
Button11_Click(Nothing, Nothing)
Case Convert.ToChar(8)
Button17_Click(Nothing, Nothing)
End Select
End Sub

Answer

In the designer or in the form's Load event you can set its KeyPreview property to True. This will cause the form to also receive key presses even though the focus is set to a child control.

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
    Me.KeyPreview = True
End Sub
Comments