trapping control-c

new topic     » topic index » view thread      » older message » newer message

I had a question for Rob Craig on disabling the trapping the Control-C
key behavior on a wait_key(). I wanted to use the key combination in my
editor as a "cut" behavior. He didn't have a solution, but he suggested
I contact this group.

I worked out a routine that reads the keyboard buffer directly. It works
like this:

        Buffer State            Action
        -------------------     ------------------------------
        Nothing pending         Return -1
        Control-C in buffer     Clear buffer, return Control-C
        Anything else           Return result of get_key()

I'm posting it in case anyone else is interested in it, as well as inviting
comments and suggestions.

This is actually part of a larger routine that also watches the SHIFT and
ALT key states, so I can catch SHIFT_LEFT_ARROW and SHIFT_RIGHT_ARROW (for
selecting text) and ALT_PRESSED (for activating the menu). Because ALT and
SHIFT don't generate actual key press events, I can't use wait_key().

This should perhaps CTRL-S as well, since that has an annoying behavior.

I also have to massage the results from this routine because the values
returned from get_key() are not unique; CTRL-M and Enter, for example,
map to the same number.

== CODE BEGINS HERE ==================================================

-- direct read of the key buffer
-- catches control-c before it can be read

        KEY_BUFFER      = 1054,     -- keyboard buffer; circular queue
        FIRST_INDEX     = 1050,     -- index to first key in buffer
        LAST_INDEX      = 1052,     -- index to last key in buffer
        CTRL_C          = 03        -- control-c

global function get_safe_key()

    -- return key currently being pressed
    -- return zero if no key is pressed

    integer key_code, scan_code

    -- buffer is empty is indexes point to each other
    if peek( FIRST_INDEX ) = peek( LAST_INDEX ) then
        -- nothing in the buffer
        return -1
    end if

    -- get the key code and the alt key code
    scan_code = peek( KEY_BUFFER + peek( FIRST_INDEX ) - 29 )
    key_code = peek( KEY_BUFFER + peek( FIRST_INDEX ) - 30 )

    -- look for control-c
    if scan_code = 46 and key_code = 3 then
        -- clear the buffer
        poke( FIRST_INDEX, peek( LAST_INDEX ) )

        -- return a control C
        return CTRL_C
        -- read through the normal process
        return get_key()
    end if

end function

== CODE ENDS HERE ====================================================


-- david cuny

new topic     » topic index » view thread      » older message » newer message


Quick Links

User menu

Not signed in.

Misc Menu