Developer technologies | VB
An object-oriented programming language developed by Microsoft that can be used in .NET.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hello,
I have made a custom button using a usercontrol and I have a problem. I want to add shortcuts to activate the button. The problem is that when I press the combination of keys, nothing happens. I have enabled key preview on the form where I have the usercontrol and I have also tried to run the code on my main form, where it functions just fine. Do you have any suggestions?
Thanks in advance!
Here is the code I used in the usercontrol:
Sub MyBase_KeyDown(sender As Object, e As KeyEventArgs)
If e.KeyData = ShortcutKeys Then
OnPictureBoxClick() 'This is basically the way I tell it to click and it works just fine'
End If
End Sub
Private Sub Custom_Button_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler Me.Parent.KeyDown, AddressOf Me.MyBase_KeyDown
End Sub
There are several ways.
A method with RegisterHotKey
(test Beep when [Ctrl] + F11 is pressed) =>
Public Class MyUserControl
Inherits System.Windows.Forms.UserControl
<DllImport("Kernel32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)>
Public Shared Function GlobalAddAtom(ByVal atomName As String) As Short
End Function
<DllImport("User32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
Public Shared Function RegisterHotKey(ByVal hWnd As IntPtr, ByVal id As Integer, ByVal fsModifiers As Integer, ByVal vk As Integer) As Boolean
End Function
<DllImport("User32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
Public Shared Function UnregisterHotKey(ByVal hWnd As IntPtr, ByVal id As Integer) As Boolean
End Function
Public Const MOD_ALT As Integer = &H1
Public Const MOD_CONTROL As Integer = &H2
Public Const MOD_SHIFT As Integer = &H4
Public Const MOD_WIN As Integer = &H8
Public Const MOD_NOREPEAT As Integer = &H4000
Public Const WM_HOTKEY As Integer = &H312
Public Const WM_CREATE = &H1
Public Const WM_DESTROY = &H2
Dim nAtom As Short
Protected Overrides Sub WndProc(ByRef m As Message)
If m.Msg = WM_CREATE Then
nAtom = GlobalAddAtom("HotKey")
RegisterHotKey(Handle, nAtom, MOD_CONTROL, Keys.F11)
Me.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
ElseIf m.Msg = WM_DESTROY Then
UnregisterHotKey(Handle, nAtom)
ElseIf m.Msg = WM_HOTKEY Then
If m.WParam = CType(nAtom, IntPtr) Then
Console.Beep(5000, 100)
End If
Else
MyBase.WndProc(m)
End If
End Sub
End Class