摘要:向Windows註冊熱鍵(RegisterHotkey)
今天在MSDN上看到下面這篇文章VB2005按鍵問題;主要是說如何在程式沒有得到焦點的情形下還能接收到我們設定的按鍵;感覺還滿有趣的,根據璉大文中提供的資料去看了一下也順便實際操作一下,還滿順利的,貼出程式碼供大家參考看看了
首先是一些相關的參考資料
下面是參考的程式碼
Module的程式碼
Imports System.Runtime.InteropServicesModule Module1<DllImport("user32", EntryPoint:="RegisterHotKey", _SetLastError:=True, _ExactSpelling:=True, _CallingConvention:=CallingConvention.StdCall)> _Public Function RegisterHotkey(ByVal hwnd As IntPtr, _ByVal Id As Int32, _<MarshalAs(UnmanagedType.U4)> ByVal fsModifiers As Int32, _<MarshalAs(UnmanagedType.U4)> ByVal vkey As Int32) As BooleanEnd Function<DllImport("user32", EntryPoint:="UnregisterHotKey", _SetLastError:=True, _ExactSpelling:=True, _CallingConvention:=CallingConvention.StdCall)> _Public Function UnregisterHotkey(ByVal hwnd As Int32, _ByVal Id As Int32) As BooleanEnd Function<DllImport("kernel32", EntryPoint:="GlobalAddAtom", _SetLastError:=True, _ExactSpelling:=False)> _Public Function GlobalAddAtom(<MarshalAs(UnmanagedType.LPTStr)> _ByVal lpString As String) As Int32End FunctionPublic Enum HotkeyModifierFlagsMOD_ALT = &H1MOD_CONTROL = &H2MOD_SHIFT = &H4MOD_WIN = &H8End EnumEnd ModuleForm的程式碼(Form上面有一個button1)
Public Class Form1
Dim myID, myID1 As Integer
Public Const WM_HOTKEY = &H312
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
myID = GlobalAddAtom("TEST")
If Not RegisterHotkey(MyBase.Handle, myID, HotkeyModifierFlags.MOD_CONTROL, Keys.A) Then
End If
myID1 = GlobalAddAtom("12345")
If Not RegisterHotkey(MyBase.Handle, myID1, HotkeyModifierFlags.MOD_CONTROL, Keys.B) Then
End If
Catch ex As Exception
System.Diagnostics.Debug.WriteLine(ex.ToString)
End Try
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
UnregisterHotkey(MyBase.Handle, myID)
UnregisterHotkey(MyBase.Handle, myID1)
End Sub
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
Select Case m.Msg
Case WM_HOTKEY
If m.WParam = myID Then
MessageBox.Show("ctrl+a")
ElseIf m.WParam = myID1 Then
MessageBox.Show("ctrl+b")
End If
End Select
MyBase.WndProc(m)
End Sub
End Class