I needed to track key press and release events, to control my player animations. I couldn't find any really extensible examples at the forum here, so I put this together.
Please offer suggestions or better solutions, if you have them. DBP only allows one to check two of the four key states, by default, so this seems to be a fairly common problem.
remstart
Press the Home key to define which key to track
Press any key other than Home, Esc, or End to begin tracking
Press End to clear defined tracking key
remend
sync on: sync rate 120
cls
type metakey state1 state2 press$ scan ink$ endtype
remstart
Type metakey tracks the state of a keyboard key.
The combination of state1 and state2 determines the press$ state.
00 = open
10 = pressed
11 = held
01 = released
press$ is tracked here as a string for the sake of the example; it may be better as an integer for use in a program.
scan is the scancode of the key being tracked.
ink$ is the inkey$ string for the key being tracked.
remend
numkeys = 2 `Change to alter number of keys to track
dim keys(numkeys) as metakey `Array to hold our metakeys
for current = 1 to numkeys
gosub _end_track `initialize array
next current
rem In game implementation, the keys array would be explicitly defined to contain keys used by the game.
do
cls
set cursor 0,0
for current = 1 to numkeys
print current,") Tracking scancode(): ",keys(current).scan,", inkey$(): ",keys(current).ink$
print " open: ",keys(current).press$ = "open"
print " pressed: ",keys(current).press$ = "pressed"
print " held: ",keys(current).press$ = "held"
print " released: ",keys(current).press$ = "released"
print ""
if scancode() = 199 and keys(current).scan = 0 `Home
repeat : until scancode() <> 199 `Wait for key release
gosub _start_track
endif
if scancode() = 207 and keys(current).scan <> 0 `End
repeat : until scancode() <> 207 `Wait for key release
gosub _end_track
endif
if keys(current).scan <> 0 then gosub _track_key
next current
sync
loop
_start_track: `Define a key for the metakey
wait key
keys(current).scan = scancode()
keys(current).ink$ = inkey$()
return
_end_track: `Set the metakey states to default
keys(current).scan = 0
keys(current).ink$ = "None"
keys(current).state1 = 0
keys(current).state2 = 0
keys(current).press$ = ""
return
_track_key: `Define the metakey states
if keystate(keys(current).scan)=1
if keys(current).state1 = 1 and keys(current).state2 = 0
keys(current).press$ = "held" : keys(current).state2 = 1
endif
if keys(current).state1 = 0 and keys(current).state2 = 0
keys(current).press$ = "pressed" : keys(current).state1 = 1
endif
endif
if keystate(keys(current).scan) = 0
if keys(current).state1 = 0 and keys(current).state2 = 1
keys(current).press$ = "open" : keys(current).state2 = 0
endif
if keys(current).state1 = 1 and keys(current).state2 = 1
keys(current).press$ = "released" : keys(current).state1 = 0
endif
endif
return