如何阻止.com格式汇编程序运行后自动关闭控制台窗口?
Hey there! That split-second window close after running your assembly program is such a classic annoyance—let's break down why it happens and how to fix it so your console stays open until you manually close it (or press a key first, if you prefer).
Why the Window Closes Immediately
Your program runs through its instructions in order: it prints "Hello, World!", then immediately calls mov ah,4Ch + int 21h—that's the DOS interrupt specifically for terminating the program. As soon as the program exits, the operating system closes the console window (especially if you launched it by double-clicking the .com file directly).
Solution 1: Add a "Wait for Keypress" Step
The simplest, most user-friendly fix is to pause the program before exiting, so it waits for you to press any key. You can use DOS interrupt int 21h with function 07h (which waits for a keypress without echoing it to the screen) or 08h (similar, but handles Ctrl+C gracefully). Here's how to modify your code:
org 100h mov dx,msg mov ah,9 int 21h ; Pause until user presses any key mov ah,07h ; DOS function: wait for keypress (no echo) int 21h mov ah,4Ch int 21h msg db 'Hello, World!',0Dh,0Ah,'$'
Now when you run the program, it will display your message and stay open until you press a key—then it exits, and the window closes. If you want to make it clearer for anyone running the program, you can add a prompt too:
org 100h mov dx,msg mov ah,9 int 21h ; Show a prompt to let the user know to press a key mov dx,prompt mov ah,9 int 21h mov ah,07h int 21h mov ah,4Ch int 21h msg db 'Hello, World!',0Dh,0Ah,'$' prompt db 'Press any key to close the window...',0Dh,0Ah,'$'
Solution 2: Infinite Loop (Not Recommended, But Works)
If you specifically want the window to stay open only until you click the X button (no keypress required), you could put the program into an infinite loop after printing the message. Keep in mind this will make the program run indefinitely (wasting CPU cycles) until you close the window manually:
org 100h mov dx,msg mov ah,9 int 21h ; Infinite loop to keep the program running loop_forever: jmp loop_forever ; We never reach the exit call now mov ah,4Ch int 21h msg db 'Hello, World!',0Dh,0Ah,'$'
This isn't ideal for most use cases, but it does achieve the "stay open until X is clicked" behavior you asked for.
Final Notes
For DOS .com programs, the keypress wait is the standard, efficient approach. The infinite loop works but is resource-heavy—stick with the keypress method unless you have a specific reason not to.
内容的提问来源于stack exchange,提问作者Max Andrews




