ON COM(n), ON KEY(n), ON PEN, ON PLAY(n), ON STRIG(n), and ON TIMER(n) StatementsObjetivo: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:
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:
Notas especiales sobre Cada Tipo de TrampaCOM que AtrapaTí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 CLAVELas 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:
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 AtraparUna 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 AtrapaLa 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 AtraparUn 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:
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:
Special Notes about Each Type of TrapCOM TrappingTypically, 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 TrappingTrappable 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:
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 TrappingA 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 TrappingUsing 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 TrappingAn 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 |