1

我之前问过一个关于vb.net 中keyhooks的问题。

我目前的问题是这样的:

我创建了一个程序,当同时按下某组键时,它应该执行某个操作。该程序必须能够在后台运行,或者在系统托盘或其他东西中运行。本质上,这应该像表单上的 KeyDown 事件一样工作,除了这种情况下的表单就是一切。

我不确定是否有办法直接从 .net API 中执行此操作,但如果有的话,我肯定还没有找到。

4

1 回答 1

3

这不需要键盘挂钩,您需要注册一个热键。更容易实现并且对系统资源的要求更低。这是一个例子,如果它被最小化,它会将表单恢复到前台。请注意,您可以注册多个密钥:

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
于 2010-02-27T21:18:47.707 回答