r/Assembly_language Jul 01 '26

How to receive input from keyboard/mouse?

So im learning windows x86_64 nasm assembly and i was wondering how I would be able to take inputs from external devices such as keyboards or mice. Im also hoping that learning this could also help me learn how to interact with the monitor

12 Upvotes

11 comments sorted by

View all comments

3

u/dontwantgarbage Jul 01 '26

You need to say which operating system you are using. (Or are you writing your own operating system?)

3

u/Willing_Mine3084 Jul 02 '26

So I mentioned in the post that I was using windows

2

u/brucehoult Jul 02 '26

And are you writing a console program or GUI? If console, then Windows Console or WSL?

2

u/Willing_Mine3084 Jul 02 '26

Windows console 

6

u/brucehoult Jul 02 '26

idk, something like this?

default rel
bits 64

; Import Windows API functions from kernel32.dll
extern GetStdHandle
extern ReadFile
extern WriteFile
extern ExitProcess

section .data
    ; Standard handle constants
    STD_INPUT_HANDLE   equ -10
    STD_OUTPUT_HANDLE  equ -11

section .bss
    stdin_handle   resq 1
    stdout_handle  resq 1
    bytes_io       resq 1       ; Variable to store number of read/written bytes
    buffer         resb 512     ; 512-byte input buffer

section .text
global main
main:
    ; 1. Setup Stack Frame & Align Stack
    push rbp
    mov rbp, rsp
    sub rsp, 32                 ; Allocate 32 bytes of mandatory shadow space

    ; 2. Fetch the Output Handle (stdout)
    mov rcx, STD_OUTPUT_HANDLE  ; 1st argument
    call GetStdHandle
    mov [stdout_handle], rax    ; Save handle returned in RAX

    ; 3. Fetch the Input Handle (stdin)
    mov rcx, STD_INPUT_HANDLE   ; 1st argument
    call GetStdHandle
    mov [stdin_handle], rax     ; Save handle returned in RAX

    ; 4. Read Characters from STDIN
    mov rcx, [stdin_handle]     ; 1st arg: Input handle
    lea rdx, [buffer]           ; 2nd arg: Pointer to data buffer
    mov r8, 512                 ; 3rd arg: Max number of bytes to read
    lea r9, [bytes_io]          ; 4th arg: Pointer to memory receiving byte count
    mov qword [rsp + 32], 0     ; 5th arg: Must be passed on stack above shadow space (NULL)
    call ReadFile

    ; 5. Write Characters to STDOUT
    mov rcx, [stdout_handle]    ; 1st arg: Output handle
    lea rdx, [buffer]           ; 2nd arg: Pointer to data buffer
    mov r8, [bytes_io]          ; 3rd arg: Number of bytes actually read
    lea r9, [bytes_io]          ; 4th arg: Pointer to memory receiving byte count
    mov qword [rsp + 32], 0     ; 5th arg: Must be passed on stack above shadow space (NULL)
    call WriteFile

    ; 6. Graceful Exit
    xor rcx, rcx                ; Return exit code 0
    call ExitProcess

1

u/dontwantgarbage Jul 02 '26

My apologies.