When the coding journey first started, I had this bizarre desire to build native Windows apps...from scratch...with nothing but win32 and my then non-existent skill set. Biting off more than I can chew? Always.
I've always struggled with GUI apps. Not the "hello world" part — everyone can make a window appear. The part that never clicked was how to lay things out and how data is supposed to flow. Every framework I picked up seemed to want me to already know something nobody had told me. So this week I sat down and went underneath all of them, all the way to the floor: raw Win32, in Rust, with nothing but Microsoft's windows crate between me and the API.
This post is the field report. It's half "yes, native Win32 development in Rust is genuinely viable" and half "the GUI concepts I'd been missing finally have names." If you've ever bounced off GUI programming, this one's for you.
The feasibility question first
The experiment: build the smallest honest Win32 app — window class, window procedure, message loop, GDI painting, click handling — with no framework and no wrapper crate. Just the windows crate, which is Microsoft's own typed bindings over the real API.
The numbers, measured rather than remembered:
| Metric | Result |
|---|---|
| Clean release build | ~6 seconds |
| Binary size | ~134 KB |
| Runtime dependencies | none — links system DLLs |
| Lines of code (heavily commented) | ~340 |
That's it. A self-contained native executable you could email to someone. No redistributables, no web stack, no runtime download. For a solo developer making tools for themselves, this trade is excellent, and I don't think it gets said loudly enough.
The friction is real, though, and it has a specific shape. The windows crate is feature-gated by Win32 namespace, and unresolved-import errors don't tell you which feature to add. Signatures drift between minor releases of the crate — my first build, written from 2021 era memory of the C API, hit five of them at once (FillRect now takes the brush by value; hCursor is no longer an Option; and so on). The escape hatch is a good one: the generated bindings are just Rust source sitting in your cargo registry, greppable. Trust the generated source over your memory of the C API.
WndProc is the origin of evil
The heart of every Win32 program is the window procedure: a bare C callback the OS invokes with (hwnd, message, wparam, lparam) whenever something happens to your window. Rust gives you no self there, no closure, no captured state. The OS hands you an opaque handle and you're on your own.
The tedium layer is obvious: every message packs its payload into wparam/lparam with a different bit-layout convention. Mouse coordinates arrive as two 16-bit halves in one isize — signed halves, because multi-monitor layouts go negative. Window sizes use the same packing with unsigned halves. Conventions are per-message; you decode by hand or write helpers.
The dangerous layer is the one nobody warns you about. Your window state comes back through that handle by way of an isize round-trip (you park a raw pointer in the window's GWLP_USERDATA slot — the full pointer choreography is in the boilerplate comments), and certain Win32 calls — UpdateWindow, MessageBox, menu tracking, window dragging — pump messages synchronously, re-entering your own WndProc down the same call stack. If you were holding a &mut AppState when you made that call, the re-entrant handler creates a second &mut to the same state. Two aliasing mutable references. Undefined behavior, by Rust's own rules — and the compiler cannot see any of it, because the pointer arrived through the OS.
If you've read Aliasing Xor Mutability, this is AxM violated through a hole the type system can't watch. The house rule that defuses it: never hold a state reference across a call that might pump messages. Prefer queue-deferring APIs — InvalidateRect (paint me later) instead of UpdateWindow (paint me now, re-entrantly).
Unsafe as an architecture
The organizing idea that came out of the session: Win32 is the floor, and all contact with the floor goes through unsafe blocks. Everything above the floor is safe Rust.
That's not a stylistic preference — it's how std itself is built. File::open is safe because somebody drew a line: below it, libc and kernel calls happen; above it, Rust's guarantees hold. The unsafe keyword isn't a warning sign. It's the boundary marker of an architecture.
The structure has three layers:
- The floor —
windows::Win32::*. Raw, unsafe, C rules. Exactly one module may name it. - The wrappers — thin owning types that uphold invariants the floor violates. A brush that deletes itself on
Drop. The test for each wrapper: can safe code above it, used however naively, cause undefined behaviour or a leak? If no, the wrapper is sound. - The app — ordinary safe Rust, under
#![forbid(unsafe_code)]. "The app logic never touches Win32 directly" stops being a convention and becomes a compiler-certified theorem.
There's one place the plan doesn't survive contact with reality, and it's the interesting one: WndProc is the floor reaching up into your code. The OS calls you directly — you can't wrap a callback the way you wrap CreateSolidBrush. That junction gets its own structure, an airlock:
// The ONE place unsafe comes up to meet you.
unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
let state = (*ptr).state.clone(); // Rc<RefCell<AppState>>
let state = state.borrow(); // reentrant borrow → LOUD PANIC, never aliasing &mut
dispatch(msg, wp, lp, &state) // safe code from here down
}
RefCell at the airlock converts the silent-undefined behaviour reentrancy hazard into a panic you can actually debug. "Safe" ends up meaning undefined behaviour impossible, panics possible, remaining invariants documented — which is exactly the standard std holds itself to. Not a cop-out; a defensible philosophy.
The part that finally made GUIs click
Here's where I confess the real gap. I built the window, but I couldn't have told you how GUI apps work in the large. Four ideas fixed that, and none of them are framework-specific:
One: a GUI app is a state machine the OS pokes. A console program runs top to bottom; main calls the OS. A GUI program inverts that: main sets up, then becomes a loop where the OS calls you. The app never does anything on its own — it sits in neutral until an event arrives, and each handler answers one question: how does my state change in response?
Two: data flows in a circle. Input event → mutate state → mark the window dirty → paint renders everything from state → the user sees it → acts → next event. The ideal is that the window is a pure function of state. Handlers mutate; paint renders; never the twain. The classic bug in every GUI stack is breaking that circle — drawing in response to input instead of recording it — and your screen and your state disagreeing from then on. Modern frameworks call this "unidirectional data flow" and sell it as a feature. In Win32 you do it by hand, which is a great way to actually learn it.
Three: there are three kinds of state, and most GUI pain is blurring them. Document state — what the app is about (the text buffer). View state — how you're currently looking at it (scroll, selection, cursor). Platform state — the HWND, the message queue, focus; the OS owns most of it. Bugs come from mixing them, and the design question in every app is who owns the text? Classic Notepad's answer: an OS EDIT control owns the buffer and your app orchestrates. The alternative — your struct owns the buffer — means you also own caret, selection, IME, clipboard, and undo. Either is fine; owning two copies of the truth is not.
Four: layout in Win32 is your WM_SIZE handler. Modern GUI systems solve layout as a two-pass negotiation — measure, then arrange — which is what flexbox, SwiftUI, and Flutter all are under different names. Win32 skips all of it: you get absolute pixels and WM_SIZE, "the client area is now W×H, do something." For a Notepad that's two lines of repositioning. For a three-pane IDE you end up writing a layout engine — which is precisely the moment people reach for frameworks, and now I know exactly what the framework is for.
Retained vs. immediate: the two paradigms
Once the basics clicked, the framework holy wars collapsed into one distinction: who remembers the UI between frames?
Retained mode: the system keeps a persistent object graph of your interface, and you send it diffs. Win32 is retained mode twice over — the OS retains your window (and decides when it needs painting), and every control (EDIT, BUTTON) is literally a child window that owns its own state and paints itself. Every classic framework — WinForms, WPF, Qt, the browser DOM — is that idea industrialized. The tax: two homes for the truth (your model and the widget's copy), and every stale-label, out-of-sync bug you've ever fought is those two disagreeing.
Immediate mode: nothing is remembered. Your code re-derives the entire UI from scratch every frame, as a side effect of drawing it. A button is a function call that draws and hit-tests in the same instant. The UI cannot disagree with your state, because the UI isn't a thing — it's a function of your state. Dynamic lists are a for loop instead of tree surgery. The costs: continuous redraw (a notepad that could idle at 0% CPU now burns cycles forever), weak text editing and accessibility (the things retained controls spent decades getting right), and manual widget identity.
The dirty secret is that everything modern is a hybrid: immediate-mode programming model, retained-mode engine underneath. React hands you a pure function of state (immediate flavor) and a reconciler diffs it into the retained browser DOM. SwiftUI and Flutter are the same shape. The industry converged on one answer because humans demonstrably write fewer sync bugs when they just describe the UI from state — the frameworks exist to give you immediate-mode ergonomics without immediate-mode's redraw bill.
My old Notepad attempt was a hand-rolled software renderer — a pixel backbuffer and a homemade bitmap font. That was immediate-mode thinking inside retained-mode scheduling, and it was a valuable exercise but a hostage foundation: every future feature would have meant rebuilding typography by hand. Text editing is retained mode's home turf. The renderer got replaced with GDI; the handmade approach stays parked for specific surfaces, not as the whole strategy.
Your server knowledge already applies
Last connection, and the one I didn't see coming: a GUI app is structurally a server you already know how to write.
| You know from Rust servers | The GUI equivalent |
|---|---|
| accept loop / reactor | the message loop |
| incoming request | a message |
| handler | the match arm in WndProc |
| "never block the reactor thread" | "never block the UI thread" |
spawn_blocking + channel back | worker thread + PostMessage back |
The law transfers whole: the event-loop thread does quick bookkeeping only; slow work goes to a worker; results come back through a channel. In a server, blocking the loop adds latency. In a GUI, blocking the message loop makes Windows ghost your window with "Not Responding" — that ghost is literally the OS catching you not pumping messages.
The one genuinely new wrinkle: reqwest drags in tokio, tokio wants to own an event loop, and Win32 already owns one — on the thread that created the window. Two loops, one thread. You can't await inside a WndProc arm (the OS expects an LRESULT back, synchronously; yielding mid-handler means someone else pumps messages while you're half-done — reentrancy again). The resolution is the same move as always: async machinery on a side thread, and PostMessage with a custom WM_APP+n message is the channel — the Win32-native mpsc whose receiving end is your message loop.
The pleasing part: it's spawn_blocking + oneshot, except every piece is visible. The queue is visible. The wake is visible. The thread handoff is a pointer riding in a message. All the machinery I've been delegating to tokio for years, laid out on the table.
Where this is going
Two repos came out of the session. win32-boilerplate is the maintained starter — the minimal app with every pain point annotated at the exact line that caused it, including the GetMessageW-returns-−1-on-error trap that would have spun my loop hot forever. rusty-notepad is the flagship: a real Notepad aligned with the boilerplate's skeleton, where the floor/wrapper/airlock architecture earns its keep — menus, a real text model, file open/save, and eventually an HTTP fetcher with a worker thread and a PostMessage bridge, because that's the smallest app that demonstrates the whole circle.
The summary I keep coming back to: a GUI app is a single-threaded state machine the OS pokes with events; its window is a pure function of its state; handlers mutate and mark dirty; paint redraws from state and nothing else; state comes in three kinds with one owner each; and layout is a space negotiation the platform either does for you or makes you do in WM_SIZE. Everything else — bindings, diffing, widgets, reactive this-and-that — is plumbing on top of that circle.
I spent years thinking I was bad at GUIs. Turns out I was paying the retained-mode diff tax without ever seeing the receipt. Now I've seen the floor, the circle, and the receipt — and the floor is closer than you'd think. Standing on it is fine.
Comments
Comments use Utterances and GitHub and are public. See the privacy policy.