Solved

Getting and displaying the byte value of a key pressed

Posted on 2004-09-02
7
452 Views
Last Modified: 2008-02-01
Hello,
I have been looking all over for an answer to this problem i am having...
I need my program to listen for the key that is being pressed, the byte value (ex. &H26 -- the down arrow) and display that on the screen (the &H26).  Basically, this program has a button the user can click, it will pop up a window that says press a key, they press a key, it displays the key, and then they click close.  Then the application will repeat the key that was pressed (programmitcally).  I have the sending of the key programmitcally working, but as you can see the key is hard coded in (&H26).

Declare Sub keybd_event Lib "user32.dll" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
'Send the key press
keybd_event(&H26, 0, 0, 0)

How can i get this number (&H26) when the user presses a key?

Thanks in advance,
Chris
0
Comment
Question by:crisco2002nnex
  • 3
  • 2
  • 2
7 Comments
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 11965733
you only need the keypresses for your window or the whole machine ?

http://www.developer.com/net/net/article.php/11087_2193301_1 discusses setting up a low level keyboard hook (you can even cancel the keys)

if its just for your form you can use the keys enumeration to compare the value of the keycode

  Private Sub Form_KeyDown(ByVal sender As Object, ByVal e As  System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
          If e.KeyCode = Keys.Escape Then End
   End Sub
0
 

Author Comment

by:crisco2002nnex
ID: 11965792
Hello,
I am using the code from that link you posted and have it in a module....
Maybe I just dont know how to get it to work right.  How do I get it to return the byte value of the key pressed amd then display it into a label?  Here is the code that i have, but it just puts 0 in the label.

    Declare Function GetKeyboardState Lib "user32" (ByRef pbKeyState As Byte) As Integer

    Private Sub frmKey1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
        Dim KeyPressed As Keyboard.KBDLLHOOKSTRUCT
        Me.Label4.Text = KeyPressed.vkCode
    End Sub

    Private Sub frmKey1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Keyboard.HookKeyboard()
    End Sub

    Private Sub frmKey1_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Closed
        Keyboard.UnhookKeyboard()
    End Sub

Thanks,
Chris
0
 
LVL 3

Accepted Solution

by:
imu79 earned 400 total points
ID: 11965801
take a look at this to capture the keys:

http://support.microsoft.com/default.aspx?scid=kb;EN-US;320583

They 'keydata' is of type 'Keys' which is an enumeration. The values are integers. You can get the hex values using the hex function as: Hex(keydata).
Then display it by appending the &H as:
MessageBox.Show("&H" & Hex(keydata))

hope that helps..
Imran.

0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
LVL 37

Expert Comment

by:gregoryyoung
ID: 11965845
if you look at the code ...

Imports System.Runtime.InteropServices
Imports System.Reflection
Imports System.Drawing
Imports System.Threading

Module Keyboard
  Public Declare Function UnhookWindowsHookEx Lib "user32" _
    (ByVal hHook As Integer) As Integer

  Public Declare Function SetWindowsHookEx Lib "user32" _
    Alias "SetWindowsHookExA" (ByVal idHook As Integer, _
    ByVal lpfn As KeyboardHookDelegate, ByVal hmod As Integer, _
    ByVal dwThreadId As Integer) As Integer

  Private Declare Function GetAsyncKeyState Lib "user32" _
    (ByVal vKey As Integer) As Integer

  Private Declare Function CallNextHookEx Lib "user32" _
    (ByVal hHook As Integer, _
    ByVal nCode As Integer, _
    ByVal wParam As Integer, _
    ByVal lParam As KBDLLHOOKSTRUCT) As Integer

  Public Structure KBDLLHOOKSTRUCT
    Public vkCode As Integer
    Public scanCode As Integer
    Public flags As Integer
    Public time As Integer
    Public dwExtraInfo As Integer
  End Structure

  ' Low-Level Keyboard Constants
  Private Const HC_ACTION As Integer      = 0
  Private Const LLKHF_EXTENDED As Integer = &H1
  Private Const LLKHF_INJECTED As Integer = &H10
  Private Const LLKHF_ALTDOWN As Integer  = &H20
  Private Const LLKHF_UP As Integer       = &H80

  ' Virtual Keys
  Public Const VK_TAB     = &H9
  Public Const VK_CONTROL = &H11
  Public Const VK_ESCAPE  = &H1B
  Public Const VK_DELETE  = &H2E

  Private Const WH_KEYBOARD_LL As Integer = 13&
  Public KeyboardHandle As Integer


  ' Implement this function to block as many
  ' key combinations as you'd like
  Public Function IsHooked( _
    ByRef Hookstruct As KBDLLHOOKSTRUCT) As Boolean

    Debug.WriteLine("Hookstruct.vkCode: " & Hookstruct.vkCode)
    Debug.WriteLine(Hookstruct.vkCode = VK_ESCAPE)
    Debug.WriteLine(Hookstruct.vkCode = VK_TAB)

    If (Hookstruct.vkCode = VK_ESCAPE) And _
      CBool(GetAsyncKeyState(VK_CONTROL) _
      And &H8000) Then

      Call HookedState("Ctrl + Esc blocked")
      Return True
    End If

    If (Hookstruct.vkCode = VK_TAB) And _
      CBool(Hookstruct.flags And _
      LLKHF_ALTDOWN) Then

      Call HookedState("Alt + Tab blockd")
      Return True
    End If

    If (Hookstruct.vkCode = VK_ESCAPE) And _
      CBool(Hookstruct.flags And _
        LLKHF_ALTDOWN) Then

      Call HookedState("Alt + Escape blocked")
      Return True
    End If

    Return False
  End Function

  Private Sub HookedState(ByVal Text As String)
    Debug.WriteLine(Text)
  End Sub

  Public Function KeyboardCallback(ByVal Code As Integer, _
    ByVal wParam As Integer, _
    ByRef lParam As KBDLLHOOKSTRUCT) As Integer

    If (Code = HC_ACTION) Then
      Debug.WriteLine("Calling IsHooked")

      If (IsHooked(lParam)) Then
        Return 1
      End If

    End If

    Return CallNextHookEx(KeyboardHandle, _
      Code, wParam, lParam)

  End Function


  Public Delegate Function KeyboardHookDelegate( _
    ByVal Code As Integer, _
    ByVal wParam As Integer, ByRef lParam As KBDLLHOOKSTRUCT) _
                 As Integer

  <MarshalAs(UnmanagedType.FunctionPtr)> _
  Private callback As KeyboardHookDelegate

  Public Sub HookKeyboard()
    callback = New KeyboardHookDelegate(AddressOf KeyboardCallback)

    KeyboardHandle = SetWindowsHookEx( _
      WH_KEYBOARD_LL, callback, _
      Marshal.GetHINSTANCE( _
      [Assembly].GetExecutingAssembly.GetModules()(0)).ToInt32, 0)

    Call CheckHooked()
  End Sub

  Public Sub CheckHooked()
    If (Hooked()) Then
      Debug.WriteLine("Keyboard hooked")
    Else
      Debug.WriteLine("Keyboard hook failed: " & Err.LastDllError)
    End If
  End Sub

  Private Function Hooked()
    Hooked = KeyboardHandle <> 0
  End Function

  Public Sub UnhookKeyboard()
    If (Hooked()) Then
      Call UnhookWindowsHookEx(KeyboardHandle)
    End If
  End Sub

End Module

there is a routine here which is blocking specific keys ... it is being called for every keypress on the machine (whether or not it is to your window, you would just put your code in it (and remove the code thats there to handle the key presses)
0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 11965858
 ' Implement this function to block as many
  ' key combinations as you'd like
  Public Function IsHooked( _
    ByRef Hookstruct As KBDLLHOOKSTRUCT) As Boolean

    Debug.WriteLine("Hookstruct.vkCode: " & Hookstruct.vkCode)
    Debug.WriteLine(Hookstruct.vkCode = VK_ESCAPE)
    Debug.WriteLine(Hookstruct.vkCode = VK_TAB)

    If (Hookstruct.vkCode = VK_ESCAPE) And _
      CBool(GetAsyncKeyState(VK_CONTROL) _
      And &H8000) Then

      Call HookedState("Ctrl + Esc blocked")
      Return True
    End If

    If (Hookstruct.vkCode = VK_TAB) And _
      CBool(Hookstruct.flags And _
      LLKHF_ALTDOWN) Then

      Call HookedState("Alt + Tab blockd")
      Return True
    End If

    If (Hookstruct.vkCode = VK_ESCAPE) And _
      CBool(Hookstruct.flags And _
        LLKHF_ALTDOWN) Then

      Call HookedState("Alt + Escape blocked")
      Return True
    End If

    Return False
  End Function

if you return true from here the keys won't be displayed ...
0
 

Author Comment

by:crisco2002nnex
ID: 11966375
Thanks for your help fellas...

I did use imu's advise ... i was simply missing the hex().

That was is a lot simpler :)

Thanks Again,
Chris
0
 
LVL 3

Expert Comment

by:imu79
ID: 11966410
sure..glad to help :)
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question