Solved

Getting and displaying the byte value of a key pressed

Posted on 2004-09-02
7
450 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

911 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now