Clock Win32 application in NativeAOT

Andrii Kurdiumov
2 min readMay 31, 2021
Nice clocks which we create in this article using Win32 API

While WinForms support forming it’s shape (all controls without support for images, cursors and related stuff), I found nice library which can be used for writing simple Win32 applications in NativeAOT.

Library is called WInterop and is written by Jeremy Kuhne. He seems to be working on WinForms, but this library has nothing in common with WinForms, except Win32 API. I believe this thin wrapper over Win32 API is worth looking at if you need get rid of frameworks and write Windows only application. This library has a lot of samples!! He has even samples from “Programming Windows, 5th Edition, Charles Petzold, 1998”

Because this library use regular Win32 API it is nicely works with NativeAOT. What’s interesting about this library, is that it’s like writing C++ code, but in C#.

Let’s look at the sample:

Pretty familiar to anyone who start with Win32. TranslateMessage/DispatchMessage, our own WndProc. Sweet memories.

Because of that, and fact that this forces code to be written in procedural style, you can use NativeAOT without much problem.

Basically if you add ILCompiler package, and disable reflection you will small application. Below is list of modifications to Clock.csproj from Samples folder.

One thing which I has to add, was custom constructor for Clock class. Reason for that is that WInterop try to be smart about HINSTANCE creation. Because of that, library use Assembly.GetCallingAssembly() which is not supported by NativeAOT. Once defaults replaced with explicit HINSTANCE obtained without call to reflection, everything working fine. See below.

I know that’s tutorial sample, but still nevertheless it is interesting how easy sometimes make applications works with NativeAOT.

Only 1.3Mb of fun

Not as pleasant as clock on that article title, but hey, I’m not a designer. Give me some slack. Resulting application take only 1.3Mb, and I do not even start adding custom runtime.

PS: If you want to know about HINSTANCE, start from Old New Thing.

PS.S.: If you lazy, compile Clock from my branch at kant2002/WInterop at test-aot (github.com)

P.S.S.S: All basic controls for WinForms works with my library https://github.com/kant2002/WinFormsComInterop there issues with images and cursors, but basic applications should works. I would be glad if somebody try compile existing applications and give feedback.

--

--

Andrii Kurdiumov

Math lover, lost in the woods of software development