Assembly code snippets

Back to the snippets overview

Details

TitleGetLastError Handling
AuthorDracon
Submitted by:JimmyClif
Date added:2002-03-04 02:25:29
Date modified:2002-03-04 02:25:29

Comments

; Most windows functions set in case of failure a global error ID. You
; can obtain this value by calling "GetLastError()". This number alone
; is of course not very usefull, but you can translate it into a
; readable message with "FormatMessage()".
;
; HandleError will exactly do this. The only parameter is the title of
; the messagebox which should be used (e.g. the name of the function).
; You will get a nice messagebox telling you what went wrong.
;
; Be aware: some messages are very strange. Unfortunately, I only know
; the german text and have translated them roughly, maybe someone can
; adjust them.
;
; Strange messages:
; * "This is only possible in Win32-mode."
; In most cases this means that you have provided an invalid windows-handle.
;
; * "The process was executed." (Der Vorgang wurde ausgeführt)
; No error has occured.
;
; Okay, have fun and use it!

Snippet

    HandleError     PROTO: DWORD

    .code

; ########################################################################

HandleError proc lpTitle:DWORD

    LOCAL lpMsgBuffer   : LPVOID

    ; calculate language ID, asm version of MAKELANGID
    mov cx, SUBLANG_DEFAULT
    shl ecx, 10
    ;or  cx, LANG_NEUTRAL       ; LANG_NEUTRAL = 0, nothing necessary

    ; Setup parameters for FormatMessage, normal pushing to use some
    ; params directly (e.g. GetLastError returns the ID in eax, but I
    ; can't use this register in "invoke")

    push NULL               ; we don't need this
    push 0                  ; min. size of output buffer if we use
                        ; FORMAT_MESSAGE_ALLOCATE_BUFFER
    lea  eax, lpMsgBuffer       ; get address of our buffer
    push eax                ; address of buffer
    push ecx                ; our language ID, calculated above
    invoke GetLastError         ; get error number
    push eax                ; push return value = error ID
    push NULL               ; can be used to format a string, we don't need it
    mov edx, FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_FROM_SYSTEM
    push edx                ; some flags, check your doc for more
    call FormatMessage          ; here we go

    ; Display error-message
    invoke MessageBox, NULL, lpMsgBuffer, lpTitle, MB_OK or MB_ICONSTOP

    ; free memory
    invoke LocalFree, lpMsgBuffer

    ret
HandleError endp