VB.NET 定义F4全局热键

VB.NET · 2023-07-01 · 561 人浏览
    Imports System.Runtime.InteropServices

Public Class Form1
    <DllImport("user32.dll")>
    Private Shared Function RegisterHotKey(ByVal hWnd As IntPtr, ByVal id As Integer, ByVal fsModifiers As Integer, ByVal vk As Integer) As Boolean
    End Function

    <DllImport("user32.dll")>
    Private Shared Function UnregisterHotKey(ByVal hWnd As IntPtr, ByVal id As Integer) As Boolean
    End Function

    ' 窗体句柄
    Private hwnd As IntPtr
    ' 热键标识符
    Private Const HOTKEY_ID As Integer = 1

    ' 注册热键
    Private Sub RegisterHotkey()
        hwnd = Me.Handle
        RegisterHotKey(hwnd, HOTKEY_ID, 0, Keys.F4)
    End Sub

    ' 取消注册热键
    Private Sub UnregisterHotkey()
        UnregisterHotKey(hwnd, HOTKEY_ID)
    End Sub

    ' 处理消息
    Protected Overrides Sub WndProc(ByRef m As Message)
        MyBase.WndProc(m)

        ' 如果收到热键消息
        If m.Msg = &H312 Then
            ' 判断热键是否为F4
            If m.WParam.ToInt32() = HOTKEY_ID Then
                ' 隐藏或显示窗体
                If Me.Visible Then
                    Me.Hide()
                Else
                    Me.Show()
                End If
            End If
        End If
    End Sub

    ' 窗体加载时注册热键
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        RegisterHotkey()
    End Sub

    ' 窗体关闭时取消注册热键
    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        UnregisterHotkey()
    End Sub
End Class
* 人工审核评论,通过后即可正常显示。软件建议请添加微信