[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] detecting keyDown, keyUp, and modifier keys



Greenblatt & Seay <g-s@navix.net> write 21 November 1998

>How does one detect and capture
>  1) which key was typed (keyDown)
>  2) when the key was released
>  3) what modifier key (or combnation) is also down at the same time
>  4) when the modifier key is released
>
>It appears I should use "Mac::Events" but all my research and experimenting
>has been in vain.

A method to handle key events in a MacWindow is set out on pages 208 and
209 of MacPerl Power & Ease, and that method usually will do all that is
necessary. If you set a hook to Windows 'key' subroutine, only key events
ocurring whilst the MacWindow is *frontmost* are handled however.

So, if you need to monitor the up/down state of keys for some other more
general purpose, (the way you put the question leads me to think this might
be the case), you would have to use raw events I think.

You would need firstly to import @Event and $CurrentEvent:

        use Mac::Events;
        use mac::Events qw(@Event $CurrentEvent);

The syntax to grab a keyDown is:

        $Event[keyDown] = \&handle_key

which passes the event (say $ev) to the subroutine 'handle_key' from which
the character can be extracted from '$ev->character'. (The subroutine
_KeyPress right at the end of Windows.pm is a perfect example.)

A modifier key down, or a combination of modifier keys down, is returned by
'$currentEvent->modifiers'. To see if the 'apple' key (for instance) was up
or down you would ask for the value of ($CurrentEvent->modifiers & 256). If
the number 256 is returned, the 'apple' key is down.

Quite how all this would be used would depend on the application, but the
following scrap of code might give some ideas. Key strokes are printed to
STDERR, except the combination 'cmd-period', which closes the progam.

    #!perl

    use Mac::Events;
    use Mac::Events qw(@Event $CurrentEvent);

    my($flag);
    $Event[keyDown] = \&down_handler;
    WaitNextEvent while !$flag;

    sub down_handler {
        my($ev) = @_;
        if (($CurrentEvent->modifiers & 256) == 256) {
            if ($ev->character == 46) {
                $flag = 1;
                print STDERR "\ngoodbye\n"
            }
            else { return 1 }
        }
        else { print STDERR chr($ev->character) }
    }

I hope this might be some help.

Alan Fry





***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch