Classic VB Corner
Stuffing the Console Keyboard Buffer
Console applications are alive and well in Administrator Land. Here’s how your console application can leave instructions for the command processor upon your exit.
While the thought of a “DOS box” may send shudders through many a soul, folks who are tasked with administering machines are still spending lots of time there. The simple truth is, console applications are hellaciously efficient for all sorts of repetitive tasks. I will confess up front that I still write quite a number of them myself, with the help of vbAdvance
and my own Console module
that offers drop-in support for most of the unique needs of console apps.
Occasionally, you want to tell the command processor to do something after your application ends. In this column, I’m going to show you how to stuff the console keyboard buffer, to achieve this goal. Specifically, I wanted a graphical version of the dirt-standard CD (change directory) command. I hate typing out full paths. So, as a bonus, we’ll build a new CDW command that provides a Select Folder dialog before performing this trick.
Here’s the basic flow of execution, after the command line processing and so on. The BrowseForFolderByPath function simply displays the dialog produced by SHBrowseForFolder, allowing the user (me!) to select which directory to change to:
Public Sub Main()
Dim Path As String
Dim drive As String
Dim keys As String
' Get user pick, and act on it...
Path = BrowseForFolderByPath(CurDir, Con.hWnd, _
"Select the folder you'd like to make current.", True, True)
If Len(Path) Then
' Change drive, if necessary...
drive = Left$(Path, 2)
If InStr(UCase$(CurDir), UCase$(drive)) <> 1 Then
keys = drive & vbCr
' Change path...
keys = keys & "cd " & CleanPath(Path) & vbCr
Con.WriteLine "Action cancelled.", , conStandardError
If Con.Compiled Then
If a good path is returned, I then break it into drive and path portions, each piece followed by a carriage return to effectively produce two distinct commands. Then, it’s simply a matter of stuffing the keyboard buffer, with that call to my own KeyStuff routine, and exiting the program. Then, it's simply a matter of stuffing the keyboard buffer, with that call to my own KeyStuff routine, and exiting Sub Main normally. However, if the user selected
Cancel on the folder selection dialog, ExitProcess is called, returning an error code to the calling process.
Public Function KeyStuff(ByVal keys As String) As Long
Dim hStdIn As Long
Dim InputRec() As InputKeyRecord
Dim EventsWritten As Long
Dim i As Long
Dim nRet As Integer
' Bail if nothing came in.
If Len(keys) = 0 Then Exit Function
' Get handle to console input.
hStdIn = GetStdHandle(STD_INPUT_HANDLE)
' Pop off keys one at a time.
ReDim InputRec(0 To (Len(keys) * 2) - 1)
For i = 0 To UBound(InputRec) Step 2
.EventType = KEY_EVENT
.wRepeatCount = 1
.bKeyDown = 1 'True
.uChar = Asc(Mid$(keys, ((i / 2) + 1), 1))
' vKeyCode is in lo-order byte.
nRet = VkKeyScan(.uChar)
.wVirtualKeyCode = ByteLo(nRet)
' Shift state is in hi-order byte.
nRet = ByteHi(nRet)
If nRet And 1 Then
' Shift key (either) pressed
.dwControlKeyState = _
.dwControlKeyState Or SHIFT_PRESSED
If nRet And 2 Then
' Control key (either) pressed
.dwControlKeyState = _
.dwControlKeyState Or RIGHT_CTRL_PRESSED
If nRet And 4 Then
' Alt key (either) pressed
.dwControlKeyState = _
.dwControlKeyState Or RIGHT_ALT_PRESSED
.wVirtualScanCode = MapVirtualKey(.wVirtualKeyCode, 0)
' Corresponding key release
InputRec(i + 1) = InputRec(i)
InputRec(i + 1).bKeyDown = False
' Stuff the buffer, and return number of events written.
nRet = WriteConsoleInput( _
hStdIn, InputRec(0), UBound(InputRec) + 1, EventsWritten)
KeyStuff = EventsWritten
' Clean up.
The general idea is to build up a series of KEY_EVENT_RECORD structures to pass to the WriteConsoleInput API function. We’ll add two records per character, one record for each key down action and a corresponding record for the related key up action. That’s why the loop above has a Step 2 iterator, as we add the second record at the end of the loop, and it’s identical in all regards except for the KeyDown element.
With each character we want to send, VkKeyScan is called to separate the character into a virtual key code (the low byte of VkKeyScan’s return) and its shift state (the high byte) based on the current keyboard. The shift state then needs to be translated a bit, as VkKeyScan returns very generalized information, but the dwControlKeyState can be highly specific in differentiating specific shift keys. This is just a straight-forward housekeeping chore, really.
Finally, we make the call to WriteConsoleInput, passing our array of input structures. The “trick” to this working is that our application exits at this point, without ever attempting to read any further input from the console. So the stuffed input is left waiting for the parent process upon our exit.
If you write console apps, perhaps this will add one more tool to your arsenal. You can download the complete KeyStuff sample from my Web site, of course. It includes a compiled copy of the CDW command line utility, so even if you’re not still using VB6 you might still want to grab the download.
Karl E. Peterson wrote Q&A, Programming Techniques, and various other columns
for VBPJ and VSM from 1995 onward, until Classic VB columns were dropped entirely
in favor of other languages. Similarly, Karl was a Microsoft BASIC MVP from 1994
through 2005, until such community contributions were no longer deemed valuable.
He is the author of VisualStudioMagazine.com's new Classic
VB Corner column. You can contact him through his Web
site if you'd like to suggest future topics for this column.