Native File Output WinAPI
Introduction
Welcome back to System Events and Integration. We are now in Lesson 4, so we already have a solid base in timers, mouse input, and keyboard input. In this lesson, we take the next practical step: saving data to disk.
Our program will remember the most recent mouse click, then write those coordinates to a local file when we press S. This is a great example of turning event handling into something lasting, because the data survives beyond the moment the click happened.
Why Native File Output Matters
As you may recall from the previous two lessons, WinAPI programs react to messages. A mouse event can collect information, and a keyboard event can trigger an action. Native file output follows the same pattern, except the action now reaches the file system.
At a high level, our program works like this:
- We capture the click position.
- We store that position in memory.
- We press
Sto save it throughCreateFileWandWriteFile.
This approach matters because we are not using higher-level C++ file streams here. We are talking directly to Windows, which helps us understand how handles, byte counts, and system resources really work.
Preparing Unicode And Shared State
Before we can save anything, we need the usual Windows headers and a place to remember the latest click. These global variables let one message store data and another message use it later. This is a common pattern in event-driven programs.
We once again start by defining the g_lastX and g_lastY variables, and set them to 0, so the program always has a valid pair of numbers, even before the first click. Later, WM_LBUTTONDOWN will update them with real coordinates.
Opening A Windows File Handle
With the shared state ready, we can build the save function. The first job is to ask Windows for a file handle. This handle represents an open connection to the file system, and we must check it before doing any write operation.
CreateFileW is a very flexible API, but here we use a simple setup. GENERIC_WRITE means write access; CREATE_ALWAYS means Windows creates the file if needed, or replaces the old contents if it already exists. That also means this version stores only the latest click, even though the name sounds like a history log. If opening fails, INVALID_HANDLE_VALUE tells us the handle is not usable, so we show an error dialog and exit the function right away.
