VB.Net隐藏程序热键

时间:2016-07-20 19:37:08

标签: vb.net keypress hotkeys

有没有办法注册热键以从不可见(隐藏)程序切换表单?我已经厌倦了常规方法,它们只在表单可见或活动窗口时才起作用。提前感谢您的帮助!

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.KeyPreview = True
    Me.ShowInTaskbar = False
    Me.ShowIcon = False
    Me.Visible = False
End Sub

这是隐藏程序的代码。

1 个答案:

答案 0 :(得分:1)

您想使用全局热键。只需确保在程序关闭时取消注册。

来自过去帮助过我的MSDN文章:

  

首先,您需要了解虚拟密钥代码。

     

http://msdn2.microsoft.com/en-us/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