Solved

Getting and displaying the byte value of a key pressed

Posted on 2004-09-02
7
456 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
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
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

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Store results in vb.net 3 25
How do sunrise and sunset times change with altitude 14 38
Access Schema 6 28
How to repeat the data 4 20
Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
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.
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

820 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