Here's one suggestion. This example uses a form with KeyPreview = True
. You need this in order to process the keystrokes.
Public Class Form1
Private CurrBtn As Button = Nothing
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
For Each btn As Button In Me.Controls.OfType(Of Button)()
AddHandler btn.Click, AddressOf Button_Click
Next
End Sub
Private Sub Form1_KeyUp(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyUp
If IsNothing(CurrBtn) Then Exit Sub
Me.Text = e.KeyCode
Select Case e.KeyCode
Case Keys.ControlKey
CurrBtn.Text = "CTRL"
Case Keys.A To Keys.Z
CurrBtn.Text = Chr(e.KeyCode)
End Select
CurrBtn = Nothing
End Sub
Private Sub Button_Click(sender As System.Object, e As System.EventArgs)
Dim btn As Button = sender
If btn.Text = "" Then
CurrBtn = btn
End If
End Sub
End Class
Precondition - all the buttons you want to dynamically assign must have the Text property set to the null string initially. The form load sub attaches the same handler to all blank buttons. CurrBtn allows you too select a button then activate it by pressing a key. You may also want to provide visual feedback by changing the button colour while it is active.