Fest
Fest

Reputation: 13

Livecode - How to use keyDown?

I've been searching for a long time now and I wanted to know, How can I code that things will happens when I press on a specific key, (e.g. W). I found many threads that help in this section with general keys like the delete key or the spacebar and some keyDown theKey, but how do I define "theKey"? Please help, FESFEW

Upvotes: 0

Views: 384

Answers (1)

William
William

Reputation: 56

For the alphanumeric keys you can use as follows:

on keyDown thekey
   switch thekey
      case "w"
         answer "w key pressed"
         break
      default
         pass keyDown
   end switch
end keyDown 

KeyDown is an event that will be generated each time the user presses a keyboard symbol (not the function keys), the thekey parameter will contain the symbol of the pressed key.

On the other hand, if you want to differentiate capital letters you must set the CaseSensitive property to TRUE

set the caseSensitive to true

The rawKeyDown property works similarly, but instead of coming in the parameter, the symbol of the pressed key what you will get will be the code of the pressed key including the function keys like shift, F# etc.

on rawKeyDown theKeyCode
   switch theKeyCode
      case 32
         answer "SPACE KEY"
         break
      case 119
         answer "w key pressed"
         break
      default
         pass rawKeyDown
   end switch
end rawKeyDown

Constants will be very useful to help make your code more readable, adding constants to previous code will look like this (note that the uppercase keys have codes other than the lowercase ):

constant kSpaceKey = 32
constant kwKey = 119
constant kWUpperKey = 87

on rawKeyDown theKeyCode
       switch theKeyCode
          case kSpaceKey 
             answer "SPACE KEY"
             break
          case kwKey 
             answer "w key pressed"
             break
          case kwKey 
             answer "w key pressed"
             break
          case kWUpperKey 
             answer "upper W key pressed"
             break
          default
             pass rawKeyDown
       end switch
    end rawKeyDown

You can also use this script in the card script to show the code of the key you press:

  on rawKeyDown theKeyCode
       put theKeyCode
  end rawKeyDown

Always remember to pass rawKeyDown, rawKeyUp,KeyDown and KeyUp events if you want to allow them to continue normal message flow

Upvotes: 4

Related Questions