ON COM(n), ON KEY(n), ON PEN, ON PLAY(n), ON STRIG(n), and ON TIMER(n) Statements

Objetivo:

Crear un acontecimiento atrapan el número de línea para un acontecimiento especificado (como comunicaciones, presionando teclas de función o teclas de control de cursor, uso del lápiz óptico, o uso de joysticks).

Sintaxis:

 ON event specifier GOSUB line number

Comentarios:

La sintaxis mostrada establece un número de línea de trampa de acontecimiento para el acontecimiento especificado. line number de 0 incapacita atrapar para este acontecimiento.

Una vez que los números de línea de trampa han sido puestos, el acontecimiento que se atrapa puede ser controlado con las líneas de sintaxis siguientes:

event specifier ON Cuando un acontecimiento es ON, y un número de línea distinto a cero es especificado para la trampa, entonces cada vez ventajas BASIC una nueva instruccion, esto comprueba para ver si el acontecimiento especificado haya ocurrido. Si esto tiene, BASIC realiza GOSUB a la línea especificada en ON la instruccion.
event specifier OFF Cuando un acontecimiento es OFF, no atrapar ocurre y el acontecimiento no es recordado, aun si esto ocurre.
event specifier STOP Cuando un acontecimiento es parado, no atrapar puede ocurrir, pero si el acontecimiento pasa, se acuerda entonces una trampa inmediata ocurre cuando un acontecimiento specifier ON es ejecutado.

Cuando una trampa es hecha para un acontecimiento particular, la trampa automáticamente causa una parada en aquel acontecimiento, entonces las trampas recurrentes nunca pueden ocurrir.

La vuelta de la rutina de trampa automáticamente hace ON a menos que un explícito OFF haya sido realizado dentro de la rutina de trampa.

Cuando una trampa de error ocurre, este automáticamente incapacita todos atrapar.

Atrapar nunca ocurrirá cuando BASIC no ejecuta un programa.

Lo siguiente es valores válidos para event specifier:

COM(n) n es el número del canal COM (1 o 2).
KEY(n) n es un número 1-20 de llave de función. 1 a 10 son las llaves de función F1 por F10. 11 a 14 son las llaves de control de cursor como sigue:

11 = CURSOR  ARRIBA      13 = CURSOR DERECHA
12 = CURSOR IZQUIERDA  14 = CURSOR ABAJO

15-20 son llaves definidas por el usuario.

PEN Ya que hay sólo una pluma, ningún número es dado.
PLAY(n) n es una expresión de número entero en la variedad de 1-32. Los valores fuera de este rango causan errores "Illegal function call".
STRIG(n) n es 0, 2, 4 o 6. (0=trigger A1; 4=trigger A2; 2=trigger B1; 6=trigger B2).
TIMER(n) n es una expresión numérica dentro de la variedad de 1 a 86,400. Un valor fuera de esta variedad causa un error "Illegal function call".
RETURN line number Esta forma opcional RETURN es querida principalmente para el uso con el acontecimiento atrapar. La rutina que atrapa acontecimiento puede querer volver en el programa GW-BASIC en un número de línea fijo todavía eliminando la entrada GOSUB que la trampa creó.

El uso RETURN no local debe ser hecho con el cuidado. Cualquier otro GOSUB, WHILE, o FOR esto era activo en el momento de la trampa permanece activo.

Si la trampa sale de una subrutina, cualquier tentativa de seguir lazos fuera de la subrutina de resultados producira un error "NEXT without FOR" .

Notas especiales sobre Cada Tipo de Trampa

COM que Atrapa

Típicamente, la rutina de trampa de COM leerá un mensaje entero del puerto COM antes de devolver.

Es recomendado esto usted no usa la trampa de COM para mensajes de carácter solos, desde en velocidades de transmisión altas el elevado de atrapar y leer para cada carácter individual puede permitir que el parachoques interrumpir para COM se desborde.

Atrapar CLAVE

Las llaves de Trappable 15 a 20 son definidas por la instruccion siguiente:

 KEY(n),CHR$[hex code]+CHR$[scan code]

n es una expresión de número entero dentro de la variedad de 15 a 20 definición de la llave para ser atrapada.

hex code es la máscara para la llave echada el pestillo: (CAPS LOCK, NUM LOCK, ALT, CTRL, LEFT SHIFT, RIGHT SHIFT)

scan code es el número que identifica una de las 83 llaves para atrapar. Refiérase Apéndice H en la Guía del Usuario GW-BASIC para códigos de exploración claves.

El bit apropiado en hex code debe ser puesto en orden para atrapar una llave que es cambiada, cambiada por el control, o alt-shifted. los valores de hex code son como sigue:

Máscara Código de maleficio Indica esto
EXTENDED &H80 La llave es ampliada
CAPS LOCK &H40 La CERRADURA mayusculas es activa
NUM LOCK &H20 La CERRADURA de NUM es activa
ALT &H08 La llave ALT es presionada
CTRL &H04 La llave CTRL es presionada
LEFT SHIFT &H02 La TECLA DE MAYÚSCULAS izquierda es presionada
RIGHT SHIFT &H01 La TECLA DE MAYÚSCULAS derecha es presionada

Para atrapar llaves cambiadas, usted puede usar el valor &H01, &H02, o &H03. Las TECLAS DE MAYÚSCULAS izquierdas y derechas son conectadas cuando &H03 es usado.

Mande KEY(n) la instruccion para más información.

Ningún tipo de atrapar es activado cuando GW-BASIC está en el modo directo. Las llaves de función reanudan su sentido de extensión estándar durante la entrada.

Una llave que causa una trampa no está disponible para el examen INPUT o instruccion INKEY$, entonces la rutina de trampa para cada llave debe ser diferente si una función diferente es deseada.

Si CTL-PRTSCR es atrapado, el botón de madera de eco de impresora en línea es tratado primero. Definiendo CTL-PRTSCR cuando una trampa clave no impide a caracteres ser repetido a la impresora si CTL-PRTSCR es presionado.

Las llaves de función 1 a 14 son predefinidas. Por lo tanto, el ajuste de la exploración cifra 59-68, 72, 75, 77, o 80 no tiene ningún efecto.

PLAY Atrapar

Una trampa de acontecimiento PLAY es publicada sólo tocando la música de fondo (PLAY"MB..). Las trampas de música de acontecimiento PLAY no son publicadas dirigiendo en el primer plano MUSIC (default case, or PLAY"MF..).

Elija valores conservadores para n. Un ON PLAY(32).. la instruccion causará trampas de acontecimiento tan a menudo que habrá poco tiempo para ejecutar el resto de su programa.

La instruccion ON PLAY(n)  causa una trampa de acontecimiento cuando la cola de música de fondo va de n a notas n-1.

STRIG que Atrapa

La utilización STRIG(n) ON  activa la rutina interrumpiré que comprueba el estado más bien cuidado. Las carreras descendentes que causan atrapar no pondrán poner las funciones STRIG(0), STRIG(2), STRIG(4), o STRIG(6) .

TEMPORIZADOR Atrapar

Un ON TIMER(n) acontecimiento que atrapa la instruccion es usado con aplicaciones que necesitan un temporizador interno. La trampa ocurre cuando los segundos n han pasado desde TIMER ON la instruccion.

Ejemplo 1:

Este es un programa terminal muy simple.

10 REM "ON COM(n)" EXAMPLE
20 OPEN "COM1:9600, O, 7" AS #1
30 ON COM(1) GOSUB 80
40 COM(1) ON
50 REM TRANSMIT CHARACTERS FROM KEYBOARD
60 A$=INKEY$: IF A$=""THEN 50
70 PRINT #1, A$;: GOTO 50
80 REM DISPLAY RECEIVE CHARACTERS
90 ALL=LOC(1): IF ALL<1 THEN RETURN
100 B$=INPUT$(ALL, #1): PRINT B$;:RETURN

Ejemplo 2:

Previene CTRL-BREAK o la reinicializacion del sistema durante un programa.

10 KEY 15, CHR$(4)+CHR$(70) REM Trap ^BREAK
20 KEY 16, CHR$(12)+CHR$(83) REM Trap system reset
30 ON KEY(15) GOSUB 1000
40 ON KEY(16) GOSUB 2000
50 KEY(15) ON
60 KEY(16) ON
.
.
.
1000 PRINT "I'm sorry, I can't let you do that"
1010 RETURN
2000 ATTEMPS=ATTEMPS+1
2010 ON ATTEMPS GOTO 2100, 2200, 2300, 2400, 2500
2100 PRINT "Mary had a little lamb": RETURN
2200 PRINT "Its fleece was white as snow": RETURN
2300 PRINT "And everywhere that Mary went": RETURN
2400 PRINT "The lamb was sure to go": RETURN
2500 KEY(16) OFF REM If they hit us once more...
2510 RETURN REM then BASIC dies...

Ejemplo 3:

Muestra el tiempo de día en línea 1 cada minuto.

10 ON TIMER(60) GOSUB 10000
20 TIMER ON
.
.
.
10000 OLDROW=CSRLIN REM Saves the current row
10010 OLDCOL=POS(0) REM Saves the current column
10020 LOCATE 1, 1: PRINT TIME$
10030 LOCATE OLDROW, OLDCOL REM Restores row and column
10040 RETURN

ON COM(n), ON KEY(n), ON PEN, ON PLAY(n), ON STRIG(n), and ON TIMER(n) Statements

 

 

 

 

 

 

Purpose:

To create an event trap line number for a specified event (such as communications, pressing function or cursor control keys, using the light pen, or using joysticks).

Syntax:

ON event specifier GOSUB line number

Comments:

The syntax shown sets up an event trap line number for the specified event. A line number of 0 disables trapping for this event.

Once trap line numbers have been set, event trapping itself can be controlled with the following syntax lines:

event specifier ON When an event is ON, and a nonzero line number is specified for the trap, then every time BASIC starts a new statement, it checks to see if the specified event has occurred. If it has, BASIC performs a GOSUB to the line specified in the ON statement.
event specifier OFF When an event is OFF, no trapping occurs and the event is not remembered, even if it occurs.
event specifier STOP When an event is stopped, no trapping can occur, but if the event happens, it is remembered so an immediate trap occurs when an event specifier ON is executed.

When a trap is made for a particular event, the trap automatically causes a stop on that event, so recursive traps can never take place.

The return from the trap routine automatically does an ON unless an explicit OFF has been performed inside the trap routine.

When an error trap takes place, this automatically disables all trapping.

Trapping will never take place when BASIC is not executing a program.

The following are valid values for event specifier:

COM(n) n is the number of the COM channel (1 or 2).
KEY(n) n is a function key number 1-20. 1 through 10 are the function keys F1 through F10. 11 through 14 are the cursor control keys as follows:

11= CURSOR UP       13= CURSOR RIGHT
12= CURSOR LEFT  14= CURSOR DOWN

15-20 are user-defined keys.

PEN Since there is only one pen, no number is given.
PLAY(n) n is an integer expression in the range of 1-32. Values outside this range result in "Illegal function call" errors.
STRIG(n) n is 0, 2, 4 or 6. (0=trigger A1; 4=trigger A2; 2=trigger B1; 6=trigger B2).
TIMER(n) n is a numeric expression within the range of 1 to 86,400. A value outside of this range results in an "Illegal function call" error.
RETURN line number This optional form of RETURN is primarily intended for use with event trapping. The event-trapping routine may want to go back into the GW-BASIC program at a fixed line number while still eliminating the GOSUB entry that the trap created.

Use of the nonlocal RETURN must be done with care. Any other GOSUB, WHILE, or FOR that was active at the time of the trap remains active.

If the trap comes out of a subroutine, any attempt to continue loops outside the subroutine results in a "NEXT without FOR" error.

Special Notes about Each Type of Trap

COM Trapping

Typically, the COM trap routine will read an entire message from the COM port before returning.

It is recommended that you not use the COM trap for single character messages, since at high baud rates the overhead of trapping and reading for each individual character may allow the interrupt buffer for COM to overflow.

KEY Trapping

Trappable keys 15 to 20 are defined by the following statement:

KEY(n),CHR$[hex code]+CHR$[scan code]

n is an integer expression within the range of 15 to 20 defining the key to be trapped.

hex code is the mask for the latched key: (CAPS LOCK, NUM LOCK, ALT, CTRL, LEFT SHIFT, RIGHT SHIFT)

scan code is the number identifying one of the 83 keys to trap. Refer to Appendix H in the GW-BASIC User's Guide for key scan codes.

The appropriate bit in hex code must be set in order to trap a key that is shifted, control-shifted, or alt-shifted. hex code values are as follows:

Mask Hex code Indicates that
EXTENDED &H80 Key is extended
CAPS LOCK &H40 CAPS LOCK is active
NUM LOCK &H20 NUM LOCK is active
ALT &H08 The ALT key is pressed
CTRL &H04 The CTRL key is pressed
LEFT SHIFT &H02 The left SHIFT key is pressed
RIGHT SHIFT &H01 The right SHIFT key is pressed

For trapping shifted keys, you may use the value &H01, &H02, or &H03. The left and right SHIFT keys are coupled when &H03 is used.

Refer to the KEY(n) statement for more information.

No type of trapping is activated when GW-BASIC is in direct mode. Function keys resume their standard expansion meaning during input.

A key that causes a trap is not available for examination with the INPUT or INKEY$ statement, so the trap routine for each key must be different if a different function is desired.

If CTL-PRTSCR is trapped, the line printer echo toggle is processed first. Defining CTL-PRTSCR as a key trap does not prevent characters from being echoed to the printer if CTL-PRTSCR is pressed.

Function keys 1 through 14 are predefined. Therefore, setting scan codes 59-68, 72, 75, 77, or 80 has no effect.

PLAY Trapping

A PLAY event trap is issued only when playing background music (PLAY"MB..). PLAY event music traps are not issued when running in MUSIC foreground (default case, or PLAY"MF..).

Choose conservative values for n. An ON PLAY(32).. statement will cause event traps so often that there will be little time to execute the rest of your program.

The ON PLAY(n) statement causes an event trap when the background music queue goes from n to n-1 notes.

STRIG Trapping

Using STRIG(n) ON activates the interrupt routine that checks the trigger status. Down-strokes that cause trapping will not set STRIG(0), STRIG(2), STRIG(4), or STRIG(6) functions.

TIMER Trapping

An ON TIMER(n) event trapping statement is used with applications needing an internal timer. The trap occurs when n seconds have elapsed since the TIMER ON statement.

Example 1:

This is a very simple terminal program.

10 REM "ON COM(n)" EXAMPLE
20 OPEN "COM1:9600, O, 7" AS #1
30 ON COM(1) GOSUB 80
40 COM(1) ON
50 REM TRANSMIT CHARACTERS FROM KEYBOARD
60 A$=INKEY$: IF A$=""THEN 50
70 PRINT #1, A$;: GOTO 50
80 REM DISPLAY RECEIVE CHARACTERS
90 ALL=LOC(1): IF ALL<1 THEN RETURN
100 B$=INPUT$(ALL, #1): PRINT B$;:RETURN

Example 2:

Prevents a CTRL-BREAK or system reset during a program.

10 KEY 15, CHR$(4)+CHR$(70) REM Trap ^BREAK
20 KEY 16, CHR$(12)+CHR$(83) REM Trap system reset
30 ON KEY(15) GOSUB 1000
40 ON KEY(16) GOSUB 2000
50 KEY(15) ON
60 KEY(16) ON
.
.
.
1000 PRINT "I'm sorry, I can't let you do that"
1010 RETURN
2000 ATTEMPS=ATTEMPS+1
2010 ON ATTEMPS GOTO 2100, 2200, 2300, 2400, 2500
2100 PRINT "Mary had a little lamb": RETURN
2200 PRINT "Its fleece was white as snow": RETURN
2300 PRINT "And everywhere that Mary went": RETURN
2400 PRINT "The lamb was sure to go": RETURN
2500 KEY(16) OFF REM If they hit us once more...
2510 RETURN REM then BASIC dies...

Example 3:

Displays the time of day on line 1 every minute.

10 ON TIMER(60) GOSUB 10000
20 TIMER ON
.
.
.
10000 OLDROW=CSRLIN REM Saves the current row
10010 OLDCOL=POS(0) REM Saves the current column
10020 LOCATE 1, 1: PRINT TIME$
10030 LOCATE OLDROW, OLDCOL REM Restores row and column
10040 RETURN
1