无论vb.net中的活动应用程序如何,都可以读取keydown

前端之家收集整理的这篇文章主要介绍了无论vb.net中的活动应用程序如何,都可以读取keydown前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我之前在vb.net问了一个关于 keyhooks的问题.

我目前的问题是这样的:

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

我不确定是否有办法直接从.net API中执行此操作,但如果有,我当然没有找到它.

这不需要键盘钩,你需要注册一个热键.更容易实现,对系统资源的要求也低得多.这是一个示例,如果最小化,它会将表单恢复到前台.请注意,您可以注册多个密钥:
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

猜你在找的VB相关文章