[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
QbasicFAQ_Inkey
How do I use INKEY$?


Back to QBasic FAQ Main Page.

Probably the first "power-tool" that newbies discover, INKEY$ is a great way to get user input into a program one key at a time. The nice thing about INKEY$ is that it removes that keystroke from the keyboard buffer. Why is that an important thing? Well, too often, a program needs pausing while the user is doing a task, reading information, or just away. It is then that most newbies place a SLEEP command. SLEEP is all well and good, used properly, but it does NOT remove key presses from the buffer! So, after you press a few keys with SLEEP command, the buffer gets filled. That in turn is announced by the ever-famous PC speaker..." Beep". (Meaning buffer filled.)

Every program needs input, and a LOOP with an INKEY$ in it will get that input.

Instead of pausing a program thusly:

SLEEP


Pause it this way:

DO WHILE INKEY$ = ""
LOOP


Better yet, get that key for use later...

DO
A$ = INKEY$
LOOP WHILE A$ = ""


Then you can use that A$ for something else.

There's a multitude of uses for that little piece of code. But probably the best way to handle a key press takes it one step further...

DO
A$ = INKEY$
IF A$ <> "" THEN GOSUB KeyPress
LOOP
'Continue from here...
KeyPress:
SELECT CASE UCASE$(A$)
CASE "Q": END
CASE CHR$(13): AcceptChanges
CASE CHR$(27):EXIT DO
END SELECT
RETURN


The SELECT CASE section handles all the key presses, and if one is not on the CASE list, well, nothing happens!

That's a few examples, there are many ways to handle program keyboard input.

There is also a nice trick to trap some of extended key presses. You can trap for example arrow keys of Fn (wher n if from 1 to 12) function keys. You can test it using the folowing program:
Dim a As String
do
   a = InKey$
   if Len(a) > 0 then
      If Len(a) = 1 Then
         Print "Normal key:    Chr$("; LTrim$(Str$(a)); ")"
         If asc(a) = 27 Then
            Print "Escape Pressed, exiting"
            Exit Do
         End If
      Else ' There are some extended keys
         Print "Extended key:  Chr$(0)+Chr$("; Ltrim$(Str$(Right$(a,1))) ;")"
      End If
   End If
Loop


(Try also use Ctr, Shift and Alt keys with extended buttons)

last edited (June 9, 2003) by PrzemekG_, Number of views: 2669, Current Rev: 3 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.