'===========================================================================
' Subject: MONITOR SHELL & GET ERRORLEVEL     Date: 12-23-92 (14:35)       
'  Author: Tony Elliott                       Code: ASM                    
'  Origin: QBTIPS_?.DOC                     Packet: ASMCODE.ABC
'===========================================================================
; MonitorShell (MONSHELL.ASM)

; Written by Tony Elliott

; EllTech Development, Inc.
; 4374 Shallowford Industrial Parkway
; Marietta, GA 30066
; (404) 928-8960 Voice or (404) 928-7111 BBS (DS)

; Released into the public domain.

; This routine is written for Microsoft QuickBASIC 4.x, BASIC 6.x and Microsoft
; PDS 7.x. Assemble using MASM 5.1:  MASM MONSHELL;

; You can link it directly to your program, place it in a LINK library (.LIB)
; or a .QLB.

; To use it:

;   DECLARE SUB MonitorShell ()
;   DECLARE FUNCTION FetchErrorLevel% ()
;
;   CALL MonitorShell
;   SHELL "PkZip -Xxy"
;   PRINT "ErrorLevel returned from SHELL:";FetchErrorLevel%

.model medium, basic
.code

Old21        Label Dword        ;Label pointing to old Int 21h handler
Old21Offset  dw ?               ;Offset part
Old21Segment dw ?               ;Segment part
MonitorSet   db 0               ;Our "hooked" flag
ExitCode     db ?               ;Where we store the exit code

MonitorShell proc uses ds

    ; From BASIC: CALL MonitorShell

    cmp cs:MonitorSet,0         ;Are we already hooked?
    jnz MonitorExit             ;If so, exit
    mov ax,3521h                ;Get current vector for int 21h
    int 21h
    mov cs:Old21Segment,es      ;Remember it for later
    mov cs:Old21Offset,bx
    mov ax,2521h
    push cs
    pop ds                      ;Point int 21h handler to our code
    mov dx, offset OurInt21
    int 21h
    mov cs:MonitorSet,-1        ;Set our flag

MonitorExit:
    ret

OurInt21:                       ;Our Int 21h handler
    cmp ah,4ch                  ;Is it a 'terminate' request?
    jnz Continue                ;If not, continue on

    mov cs:ExitCode,al          ;Remember the exit code
    push ax
    push ds
    mov ax,2521h                ;Unhook ourself after the first hit
    mov ds,Old21Segment
    mov dx,Old21Offset
    int 21h                     ;Point Int 21h back to original
handler
    pop ds
    pop ax
    mov cs:MonitorSet,0         ;Set out flag back to zero
    
Continue:
    jmp dword ptr [Old21]       ;Transfer control to original Int 21h

MonitorShell endp

FetchErrorLevel proc

    ;From BASIC: DECLARE FUNCTION FetchErrorLevel%
    ;            PRINT "Last errorlevel:"; FetchErrorLevel%

    mov al,cs:ExitCode          ;Put the errorlevel into al
    xor ah,ah                   ;Zero ah
    ret                         ;ErrorLevel returned as result

FetchErrorLevel endp
    end
