程式語言 - Netwide Assembler (NASM) - Win32 API - Painting - Set Pixel



參考資訊:
https://masm32.com/board/index.php
https://www.nasm.us/xdoc/2.13rc9/html/nasmdoc0.html

屏幕的最小顯示單位是像素,像素由紅色(Red)、綠色(Green)、藍色(Blue)、Alpha等四個顏色組成,因此,在呼叫CreateWindow()時,傳入的解析度,如:300x300,代表該視窗(有效區域)的X軸有300個像素,而Y軸則是有300個像素,這個300x300像素的區域是可以用來繪製任何東西,WM_PAINT是處理視窗重新繪畫的事件,繪畫的相關處理都需要在這個事件完成,比較特別的是,Windows視窗將繪圖的許多東西抽象化,最基本的需求是:一個DC(Device Context)和一個BITMAP,DC可以想像成是一個畫台,而BITMAP則是一片畫布(Buffer),DC有了Buffer就可以畫上任何東西並將其顯示在視窗上

main.asm

    %include "head.asm" 

    segment .text
WndProc:
    push ebp
    mov ebp, esp
       
    cmp dword [ebp + ARG2], WM_PAINT
    je .handle_paint
    cmp dword [ebp + ARG2], WM_CLOSE
    je .handle_close
    cmp dword [ebp + ARG2], WM_DESTROY
    je .handle_destroy
    jmp .handle_default
  
.handle_paint:
    push ps
    push dword [ebp + ARG1]
    call BeginPaint
    mov [hDC], eax
  
    xor eax, eax
    mov [y], eax
.ylp:
    xor eax, eax
    mov [x], eax
.xlp:
    push 0ffh
    push dword [x]
    push dword [y]
    push dword [hDC]
    call SetPixel
    inc dword [x]
    cmp dword [x], 100
    jb .xlp
    inc dword [y]
    cmp dword [y], 100
    jb .ylp
      
    push ps
    push dword [ebp + ARG1]
    call EndPaint
    xor eax, eax
    jmp .finish
  
.handle_close:
    push dword [ebp + ARG1]
    call DestroyWindow
    xor eax, eax
    jmp .finish
       
.handle_destroy:
    push 0
    call PostQuitMessage
    xor eax, eax
    jmp .finish
       
.handle_default:
    push dword [ebp + ARG4]
    push dword [ebp + ARG3]
    push dword [ebp + ARG2]
    push dword [ebp + ARG1]
    push dword [pDefWndProc]
    call CallWindowProc
       
.finish:
    leave
    ret 16
       
WinMain:
    push ebp
    mov ebp, esp
        
    push 0
    push 0
    push 0
    push 0
    push 300
    push 300
    push 0
    push 0
    push WS_OVERLAPPEDWINDOW | WS_VISIBLE
    push szAppName
    push WC_DIALOG
    push WS_EX_LEFT
    call CreateWindowEx
    mov [hWin], eax
       
    push WndProc
    push GWL_WNDPROC
    push dword [hWin]
    call SetWindowLong
    mov [pDefWndProc], eax
    
.loop:
    push 0
    push 0
    push 0
    push msg
    call GetMessage
    cmp eax, 0
    je .exit
        
    push msg
    call DispatchMessage
    jmp .loop
        
.exit:
    mov eax, [msg + MSG.wParam]
    leave
    ret 16
        
_start:
    push 0
    call GetModuleHandle
    mov [hInstance], eax
        
    call GetCommandLine
    mov [pCommand], eax
        
    push SW_SHOWNORMAL
    push dword [pCommand]
    push 0
    push dword [hInstance]
    call WinMain
        
    push eax
    call ExitProcess

Line 8~9:處理繪畫事件
Line 17~20:取得視窗的DC,該DC已經有Buffer可以使用,因此,可以直接在上面繪製任何東西
Line 28~32:透過SetPixel()畫出一個正方形,顏色是紅色
Line 40~42:結束繪製

完成