[RESOLVED] Overrides WndProc From within Class
Currently im trying to write a HotKey class, however in order to intercept the messages you need to overwrite the WndProc and check for WM_HOTKEY.
Currently, im using Inherits Form inside of the class, so that it has the option of overwriding the wndproc, but along with that I get all the forms normal events when trying to handle it.
Below is my code:
Code:
Public Class Form1
Private Class HotKey
Inherits Form
Private Declare Function RegisterHotKey Lib "user32" (ByVal hwnd As IntPtr, ByVal id As Integer, ByVal fsModifiers As Integer, ByVal vk As Integer) As Integer
Private Declare Function UnregisterHotKey Lib "user32" (ByVal hwnd As IntPtr, ByVal id As Integer) As Integer
Private Declare Function GlobalAddAtom Lib "kernel32" Alias "GlobalAddAtomA" (ByVal lpString As String) As Short
Private Declare Function GlobalDeleteAtom Lib "kernel32" (ByVal nAtom As Short) As Short
Private Const WM_HOTKEY As Integer = &H312
Public hkID As Integer = 0
Public Shared Event HotKey_Pressed()
Public Enum ModKeys
MOD_ALT = 1
MOD_CONTROL = 2
MOD_SHIFT = 4
MOD_WIN = 8
MOD_NONE = 0
End Enum
Public Sub New(ByVal ModKey As ModKeys, ByVal Key As Keys)
Dim atomName As String = Process.GetCurrentProcess.Id.ToString("X8") & Me.Name
hkID = GlobalAddAtom(atomName)
If RegisterHotKey(Me.Handle, hkID, ModKey, CInt(Key)) = 0 Then
hkID = 0
MsgBox("Unable to register hotkey. Error code: " & System.Runtime.InteropServices.Marshal.GetLastWin32Error.ToString)
Me.Finalize()
End If
End Sub
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
MyBase.WndProc(m)
If m.Msg = WM_HOTKEY Then
If m.WParam.ToString = hkID Then
RaiseEvent HotKey_Pressed()
End If
End If
End Sub
Protected Overrides Sub Finalize()
Try
GlobalDeleteAtom(hkID)
UnregisterHotKey(Me.Handle, hkID)
Catch ex As Exception
End Try
MyBase.Finalize()
End Sub
End Class
Private WithEvents hk1 As New HotKey(HotKey.ModKeys.MOD_WIN, Keys.BrowserHome)
Private Sub hk1_HotKey_Pressed() Handles hk1.HotKey_Pressed
MsgBox("test")
End Sub
End Class
That works perfectly fine, its just that I dont want hk1 to be able to handle other things other than the HotKey_Pressed event...
Re: Overrides WndProc From within Class
You should inherit the NativeWindow class as it exists specifically for this purpose.
http://msdn.microsoft.com/en-us/libr...ivewindow.aspx
Re: Overrides WndProc From within Class
Perfect, thank you.
Have to remember this one -_-