Reading keydown regardless of active application in vb.net

前端 未结 1 1903
谎友^
谎友^ 2020-12-20 07:21

I asked a question earlier about keyhooks in vb.net.

My current issue is such:

I have created a program which should perform a certain action whenever a cert

相关标签:
1条回答
  • 2020-12-20 08:04

    That doesn't require a keyboard hook, you'll want to register a hot key. Much easier to implement and much less demanding of system resources. Here's an example, it restores the form to the foreground if it was minimized. Note that you can register more than one key:

    Imports System.Runtime.InteropServices
    Imports System.ComponentModel
    
    Public Class Form1
      Private Const cHotKeyId As Integer = 0
    
      Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        '--- Register Ctrl + Shift + U as a hot key
        If Not RegisterHotKey(Me.Handle, cHotKeyId, MOD_CONTROL + MOD_SHIFT, Keys.U) Then
          Throw New Win32Exception()
        End If
        MyBase.OnLoad(e)
      End Sub
    
      Protected Overrides Sub OnFormClosing(ByVal e As System.Windows.Forms.FormClosingEventArgs)
        UnregisterHotKey(Me.Handle, cHotKeyId)
        MyBase.OnFormClosing(e)
      End Sub
    
      Protected Overrides Sub WndProc(ByRef m As Message)
        Console.WriteLine(m.ToString())
        If (m.Msg = WM_HOTKEY AndAlso m.WParam = CType(cHotKeyId, IntPtr)) Then
          Me.Visible = True
          If Me.WindowState = FormWindowState.Minimized Then Me.WindowState = FormWindowState.Normal
          SetForegroundWindow(Me.Handle)
        End If
        MyBase.WndProc(m)
      End Sub
    
      '--- P/Invoke declarations
      Private Const WM_HOTKEY As Integer = &H312
      Private Const MOD_ALT As Integer = &H1
      Private Const MOD_CONTROL As Integer = &H2
      Private Const MOD_SHIFT As Integer = &H4
      Private Declare Function RegisterHotKey Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal id As Integer, ByVal fsModifier As Integer, ByVal vk As Integer) As Boolean
      Private Declare Function UnregisterHotKey Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal id As Integer) As Boolean
      Private Declare Function SetForegroundWindow Lib "user32.dll" (ByVal hWnd As IntPtr) As Boolean
    
    End Class
    
    0 讨论(0)
提交回复
热议问题