Dasith
Dasith

Reputation: 1095

Global Keyboard button press events

I have some issues trying to get a key press event to trigger by importing and using components from an external library.I'm using this as a help in tracking global prntscreen key press events.

So i have added the reference to my vb.net project as seen here also i imported the library on my from.And it shows up on toolbar as a component. However i have trouble figuring out to getting the keypress event to work

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

these is the code i added to detect prntsceen button press but however it dosent get triggered , what am i doing wrong ?

Upvotes: 0

Views: 213

Answers (1)

Hans Passant
Hans Passant

Reputation: 941585

The print-screen key is special, a global hook doesn't capture it. You can make it work by pinvoking RegisterHotKey() instead. A sample form that shows the required code:

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

Upvotes: 4

Related Questions