向Windows註冊熱鍵(RegisterHotkey)

摘要:向Windows註冊熱鍵(RegisterHotkey)

今天在MSDN上看到下面這篇文章VB2005按鍵問題;主要是說如何在程式沒有得到焦點的情形下還能接收到我們設定的按鍵;感覺還滿有趣的,根據璉大文中提供的資料去看了一下也順便實際操作一下,還滿順利的,貼出程式碼供大家參考看看了
首先是一些相關的參考資料

 


下面是參考的程式碼
Module的程式碼

Imports System.Runtime.InteropServices
 
Module 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 Boolean
 
    End Function
 
    <DllImport("user32", EntryPoint:="UnregisterHotKey", _
        SetLastError:=True, _
        ExactSpelling:=True, _
        CallingConvention:=CallingConvention.StdCall)> _
    Public Function UnregisterHotkey(ByVal hwnd As Int32, _
                                ByVal Id As Int32) As Boolean
 
    End Function
 
    <DllImport("kernel32", EntryPoint:="GlobalAddAtom", _
        SetLastError:=True, _
        ExactSpelling:=False)> _
    Public Function GlobalAddAtom(<MarshalAs(UnmanagedType.LPTStr)> _
                ByVal lpString As String) As Int32
 
    End Function
 
    Public Enum HotkeyModifierFlags
        MOD_ALT = &H1
        MOD_CONTROL = &H2
        MOD_SHIFT = &H4
        MOD_WIN = &H8
    End Enum
End Module
 
Form的程式碼(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