简体   繁体   中英

Masm32: SetConsoleTextAttribute

I am newbie in assembler. I need to change text color in loop (5 time - 5 different colors) using Masm32. My code:

Main PROC
    LOCAL hStdout:DWORD
    call SetConsoleTitleA
    push -11
    call GetStdHandle
    mov hStdout,EAX

    mov BX,5
        lp:

        push hStdout
        push 2
        call SetConsoleTextAttribute

        push 0
        push 0
        push 24d
        push offset sWriteText
        push hStdout
        call WriteConsoleA

        dec BX
    jnz lp

    push 2000d
    call Sleep

    push 0
    call ExitProcess

    Main ENDP
end Main

PS Sorry for my Enlish.

Problem 1

As hinted to by Raymond Chen is that the call to SetConsoleTitle is incorrect.

Main PROC
    LOCAL hStdout:DWORD
    call SetConsoleTitleA

Notice that you don't push any arguments onto the stack for SetConsoleTitle . This means that after this call the stack is corrupted.

Once this is fixed we can move on to problem 2.

Problem #2

According to the __stdcall calling convention arguments are pushed right-to-left. But in the code the arguments are being pushed left-to-right. In the code above this is the call sequence for SetConsoleTextAttribute

push hStdout
push 2
call SetConsoleTextAttribute

Given the function's signature:

BOOL WINAPI SetConsoleTextAttribute(
  _In_ HANDLE hConsoleOutput,
  _In_ WORD   wAttributes
);

The code is calling this function like the following C code,

SetConsoleTextAttribute(2, hStdout);

which is reversed. The call should be:

push 2
push hStdout
call SetConsoleTextAttribute

Problem 3

The code ignores all return values, except for GetStdHandle . For SetConsoleTextAttribute the return value is nonzero if the function was successful. If the function returns zero, then the function call failed, and for this function 1 extended error information is available by calling GetLastError . The documentation on MSDN has information about each of the other functions and how they indicate errors.


1 Not all functions call SetLastError when they fail. There are a lot of issues caused by thinking otherwise. Also of note that functions that do set the error, only do so when they have an error.

Also worth a read is The History Of Calling Conventions series over at The Old New Thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM