• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 365
  • Last Modified:

Visual basic: how to capture any keyboard stroke without stopping the execution of the program

Hello Experts,
I need to continue the execution of my visual basic 2012 App without stopping execution but if the user types any key while executing I need to be able tocatch it.... somethingh like the old inkey$(),
How can I do this in VB2012 ?
  • 2
  • 2
1 Solution
This can be done assuming that a form is displayed on the screen. You need to add an event handler to each control to capture the keypress event

Imports System
Imports System.Windows.Forms

Public Class Form1
    Inherits Form

    Public Sub New()
        ' Create a TextBox control. 
        Dim tb As New TextBox()
        AddHandler tb.KeyPress, AddressOf keypressed
    End Sub 'New 

    Private Sub keypressed(ByVal o As [Object], ByVal e As KeyPressEventArgs)
        ' The keypressed method uses the KeyChar property to check  
        ' whether the ENTER key is pressed.  

        ' If the ENTER key is pressed, the Handled property is set to true,  
        ' to indicate the event is handled. 

        If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then
            e.Handled = True 
        End If 
    End Sub 'keypressed

    End Class 'Form1

Open in new window

You can then add your code in the KeyPressed method, setting e.handled = true if you want to consume the keypress and not pass it to the control.
RGuillermoProject ManagerAuthor Commented:
we are using console mode, please your advice
It would be helpful if you put all relevant information in your post :)

You would need to include this in your code

        If Console.KeyAvailable Then
            KeyPressed = Console.ReadKey(True).KeyChar
            ' Process the key
        End If

ReadKey blocks, so that's why the check for keyavailable is performed.
RGuillermoProject ManagerAuthor Commented:
Thank you very much!!

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now