全局键盘按钮按事件

时间:2014-05-18 10:03:30

标签: .net vb.net

我在尝试通过导入和使用外部库中的组件来触发按键事件时遇到了一些问题。我使用this作为跟踪全局prntscreen键按事件的帮助。

所以我添加了对我的vb.net项目的引用,如here所示,我也在我的from.Ind上导入了库。它在工具栏上显示为一个组件。但是我无法确定让按键事件发挥作用

Imports Gma.UserActivityMonitor
Partial Public Class Main

Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load

    AddHandler HookManager.KeyDown, AddressOf HookManager_KeyDown


    Me.NotifyIcon1.Visible = True
    Me.WindowState = FormWindowState.Minimized
End Sub

 Private Sub HookManager_KeyDown(sender As Object, e As KeyEventArgs)

    If e.KeyCode = Keys.PrintScreen Then
        Dim img As Image = SnippingTool.Snip()
        PictureBox1.Image = img
    End If
End Sub
End class

这些是我添加的代码,用于检测prntsceen按钮按下但是它会被触发,我做错了什么?

1 个答案:

答案 0 :(得分:4)

打印屏幕键是特殊的,全局挂钩不捕获它。您可以通过pinvoking RegisterHotKey()来使其工作。显示所需代码的示例表单:

Imports System.ComponentModel
Imports System.Runtime.InteropServices

Public Class Form1
    Private Sub PrintScreen()
        AppActivate(System.Diagnostics.Process.GetCurrentProcess().Id)
        MessageBox.Show("Print screen key pressed...")
    End Sub

    Protected Overrides Sub OnHandleCreated(e As EventArgs)
        MyBase.OnHandleCreated(e)
        If Not RegisterHotKey(Me.Handle, HOTKEYID, 0, VK_SNAPSHOT) Then Throw New Win32Exception
    End Sub

    Protected Overrides Sub OnFormClosing(e As FormClosingEventArgs)
        MyBase.OnFormClosing(e)
        If Not e.Cancel Then UnregisterHotKey(Me.Handle, HOTKEYID)
    End Sub

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = WM_HOTKEY Then
            Dim id = m.WParam.ToInt32()
            If id = HOTKEYID Then PrintScreen()
        End If
        MyBase.WndProc(m)
    End Sub


    ''--- Pinvoke:
    Private Const HOTKEYID As Integer = 0
    Private Const WM_HOTKEY As Integer = &H312
    Private Const VK_SNAPSHOT As Integer = &H2C

    <DllImport("User32.dll")> _
    Private Shared Function RegisterHotKey(ByVal hwnd As IntPtr, ByVal id As Integer, ByVal modifiers 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
End Class