可不可以教教我怎么用显示字符串的子程序,在屏幕中间分别显示绿色,绿底红色,白底蓝色的字符串‘welcome to masm’
下面是使用汇编语言(MASM)的代码,以在屏幕中间显示绿色、绿底红色和白底蓝色的字符串“welcome to masm”:
.model small
.stack 100h
.data
welcome db "welcome to masm"
green db 27h, 91h, 50h, 27h, 91h, 49h, 50h, 52h, 109h, 0ah, 0dh, '$'
green_red db 27h, 91h, 50h, 50h, 59h, 52h, 49h, 109h, "welcome", 27h, 91h, 48h, 109h, 0ah, 0dh, '$'
blue_white db 27h, 91h, 52h, 52h, 109h, 27h, 91h, 52h, 109h, "welcome", 27h, 91h, 48h, 109h, 0ah, 0dh, '$'
.code
main proc
mov ax, @data
mov ds, ax
; 显示绿色字符串
mov ah, 9h
lea dx, green
int 21h
; 显示绿底红色字符串
mov ah, 9h
lea dx, green_red
int 21h
; 显示白底蓝色字符串
mov ah, 9h
lea dx, blue_white
int 21h
mov ah, 4ch ; 退出程序
int 21h
main endp
end main
在代码中,使用了ANSI转义序列来设置不同的颜色和背景颜色。例如,27h, 91h, 50h 表示设置颜色为绿色,27h, 91h, 49h, 50h, 52h, 109h 表示设置颜色为红色,背景颜色为绿色。
.386
.model flat, stdcall
option casemap:none
include \masm32\include\windows.inc
include \masm32\include\user32.inc
include \masm32\include\kernel32.inc
includelib \masm32\lib\user32.lib
includelib \masm32\lib\kernel32.lib
.data
text db 'welcome to masm', 0
text_len equ $ - offset text
screen_width dd ?
screen_height dd ?
.code
start:
; 获取屏幕宽度和高度
call get_screen_size
; 计算字符串的位置
mov ebx, screen_width
sub ebx, text_len
shr ebx, 1
mov ecx, screen_height
shr ecx, 1
; 显示绿色字符串
mov eax, 02h ; 绿色文本
call set_color
mov eax, offset text
call print_string
; 显示绿底红色字符串
moveax, 02h ; 绿色文本
call set_color
mov ebx, 04h ; 绿底红色底纹
call set_background
mov eax, offset text
call print_string
; 显示白底蓝色字符串
mov eax, 01h ; 蓝色文本
call set_color
mov ebx, 07h ; 白色底纹
call set_background
mov eax, offset text
call print_string
; 退出程序
call exit_program
; 获取屏幕宽度和高度的子程序
; 输入:无
; 输出:屏幕宽度和高度
get_screen_size proc
invoke GetSystemMetrics, SM_CXSCREEN
mov [screen_width], eax
invoke GetSystemMetrics, SM_CYSCREEN
mov [screen_height], eax
ret
get_screen_size endp
; 设置文本颜色的子程序
; 输入:eax =颜色代码
; 输出:无
set_color proc color:dword
invoke SetConsoleTextAttribute, GetStdHandle(STD_OUTPUT_HANDLE), color
ret
set_color endp
; 设置背景颜色的子程序
; 输入:eax = 背景颜色代码set_background proc color:dword
invoke SetConsoleTextAttribute, GetStdHandle(STD_OUTPUT_HANDLE), color shl 4
ret
set_background endp
; 显示字符串的子程序
; 输入:eax = 字符串地址
; 输出:无
print_string proc str_ptr:dword
; 获取字符串长度
mov ecx, -1
mov edx, str_ptr
dec edx
repne scasb
not ecx
; 计算字符串的结束位置
mov ebx, [screen_width]
sub ebx, ecx
shr ebx, 1
add ebx, ecx
; 设置光标位置
invoke SetConsoleCursorPosition, GetStdHandle(STD_OUTPUT_HANDLE), DWORD PTR 0
invoke COORD, WORD PTR ebx, WORD PTR [screen_height]
; 显示字符串
invoke WriteConsole, GetStdHandle(STD_OUTPUT_HANDLE), str_ptr, ecx, NULL, NULL
ret
print_string endp
; 退出程序的子程序
; 输入:无
; 输出:无
exit_program proc
invoke ExitProcess, 0
exit_program endp
end start