locked
FAQs: 如何在VB.NET中注册热键? RRS feed

答案

  • 首先您需要知道虚拟按键码。

    http://msdn.microsoft.com/zh-cn/library/ms927178.aspx

    然后你可以P/Invoke RegisterHotKey/UnregisterHotKey API来注册热键或者移除注册。

    代码示例: 注册多个热键,例如:Alt+D, Alt+C, 等等.

    Imports System.Runtime.InteropServices

              

    Public Class Form1

     

        Public Const MOD_ALT As Integer = &H1 'Alt key

        Public Const WM_HOTKEY As Integer = &H312

     

        <DllImport("User32.dll")> _

        Public Shared Function RegisterHotKey(ByVal hwnd As IntPtr, _

                            ByVal id As Integer, ByVal fsModifiers As Integer, _

                            ByVal vk As Integer) As Integer

        End Function

     

        <DllImport("User32.dll")> _

        Public Shared Function UnregisterHotKey(ByVal hwnd As IntPtr, _

                            ByVal id As Integer) As Integer

        End Function

     

        Private Sub Form1_Load(ByVal sender As System.Object, _

                            ByVal e As System.EventArgs) Handles MyBase.Load

            RegisterHotKey(Me.Handle, 100, MOD_ALT, Keys.D)

            RegisterHotKey(Me.Handle, 200, MOD_ALT, Keys.C)

        End Sub

     

        Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)

            If m.Msg = WM_HOTKEY Then

                Dim id As IntPtr = m.WParam

                Select Case (id.ToString)

                    Case "100"

                        MessageBox.Show("You pressed ALT+D key combination")

                    Case "200"

                        MessageBox.Show("You pressed ALT+C key combination")

                End Select

            End If

            MyBase.WndProc(m)

        End Sub

     

        Private Sub Form1_FormClosing(ByVal sender As System.Object, _

                            ByVal e As System.Windows.Forms.FormClosingEventArgs) _

                            Handles MyBase.FormClosing

            UnregisterHotKey(Me.Handle, 100)

            UnregisterHotKey(Me.Handle, 200)

        End Sub

    End Class

     

    相关帖子:

    http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/ced3b443-b295-4078-9632-afc3f0f44ac6/


    如果您对我们的论坛在线支持服务有任何的意见或建议,请通过邮件告诉我们。
    MSDN 论坛好帮手 立刻免费下载  MSDN 论坛好帮手
    2011年3月2日 12:30