程式語言 - MASM32 - Painting - Set Pixel



參考資訊:
http://www.winprog.org/tutorial/
http://winapi.freetechsecrets.com/win32/
https://github.com/gammasoft71/Examples_Win32

屏幕的最小顯示單位是像素,像素由紅色(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

    .386
    .model flat,stdcall
    option casemap:none
       
include c:\masm32\include\msvcrt.inc
include c:\masm32\include\windows.inc
include c:\masm32\include\kernel32.inc
include c:\masm32\include\gdi32.inc
include c:\masm32\include\user32.inc
       
includelib c:\masm32\lib\msvcrt.lib
includelib c:\masm32\lib\gdi32.lib
includelib c:\masm32\lib\user32.lib
includelib c:\masm32\lib\kernel32.lib
       
    .data
szCaption   db "main",0
hWin        dd 0
hInstance   dd 0
CommandLine dd 0
defWndProc  dd 0
       
    .code
WndProc proc hWnd:HWND, uMsg:UINT, wParam:WPARAM, lParam:LPARAM
    local hdc:dword
    local x:dword
    local y:dword
    local ps:PAINTSTRUCT

    .if uMsg == WM_PAINT
        invoke BeginPaint, hWnd, addr ps
        mov hdc, eax

        xor eax, eax
        mov y, eax
    ylp:
        xor eax, eax
        mov x, eax
    xlp:
        invoke SetPixel, hdc, x, y, 0ffh
        inc x
        cmp x, 100
        jb xlp
        inc y
        cmp y, 100
        jb ylp

        invoke EndPaint, hWnd, addr ps
        xor eax, eax
        ret
    .elseif uMsg == WM_CLOSE
        invoke DestroyWindow, hWnd
        xor eax, eax
        ret
    .elseif uMsg == WM_DESTROY
        invoke PostQuitMessage, 0
        xor eax, eax
        ret
    .endif
     
    invoke CallWindowProc, defWndProc, hWnd, uMsg, wParam, lParam
    ret
WndProc endp
      
WinMain proc hInst:DWORD, hPrevInst:DWORD, CmdLine:DWORD, CmdShow:DWORD
    local msg:MSG
       
    invoke CreateWindowEx, WS_EX_LEFT, WC_DIALOG, offset szCaption, 
        WS_OVERLAPPEDWINDOW or WS_VISIBLE, 0, 0, 300, 300, NULL, NULL, NULL, NULL
    mov hWin, eax
      
    invoke SetWindowLong, hWin, GWL_WNDPROC, WndProc
    mov defWndProc, eax
@@:
    invoke GetMessage, addr msg, NULL, 0, 0
    cmp eax, 0
    je @f
    invoke DispatchMessage, addr msg
    jmp @b
@@:
    mov eax, msg.wParam
    ret
WinMain endp
     
start:
    invoke GetModuleHandle, NULL
    mov hInstance, eax
       
    invoke GetCommandLine
    mov CommandLine, eax
       
    invoke WinMain, hInstance, NULL, CommandLine, SW_SHOWDEFAULT
    invoke ExitProcess, eax
end start

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

完成