c.goss
c.goss

Reputation: 29

How to Create a Property in a Custom Form

The idea is to be able to set the f1-f4 keys to be settable at design time. Like the accept and canel buttons are in a normal form.

me.AcceptButton = Button1

I want to be able to have the same functionality as this property. as in accept button you press enter and it executes. I would like to be able to assign the F1-F4 keys to buttons.

me.F1Button = ButtonCalc
me.F2Button = ButtonClr
etc.

I have looked quite a bit into creating custom controls and have build a few but seem to have found no documentation on how to something similar. I am looking for any books, articles or guides about this.

Upvotes: 1

Views: 391

Answers (2)

LarsTech
LarsTech

Reputation: 81620

You have to inherit the form as your base class to get the designer to serialize the property, but this would be a simple example:

Public Property F1Button As Button

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, _
                                           keyData As Keys) As Boolean
  If keyData = Keys.F1 AndAlso F1Button IsNot Nothing Then
    F1Button.PerformClick()
    Return True
  End If
  Return MyBase.ProcessCmdKey(msg, keyData)
End Function

Upvotes: 2

djv
djv

Reputation: 15774

Set up KeyDown event handlers for the form and all the buttons. You need to do this because the form may not have focus when the key is pressed.

Private Sub Form1_Load(sender As Object, e As EventArgs)
    AddHandler CancelButton.KeyDown, AddressOf Form1_KeyDown
    AddHandler OKButton.KeyDown, AddressOf Form1_KeyDown
    AddHandler Me.KeyDown, AddressOf Form1_KeyDown
End Sub

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs)
    Select Case e.KeyCode
        Case Keys.F1
            ' custom action
        Case Keys.F2
            ' custom action
        Case Keys.F3
            ' custom action
        Case Keys.F4
            ' custom action
    End Select
End Sub

Upvotes: 0

Related Questions