Saving & Restoring Window State
How to make your WinUI app remember its window state between sessions.
👉 GitHub Repo: WindowStateSaver
Goal
We’ll build a simple system that:
- Saves window position, size, scale (DPI), and maximized state when the app closes.
- Restores them automatically when it starts again.
🪟 OurApp/
├── 📁 Models/
│ └── 📄 WindowState.cs
├── 📁 Services/
│ └── 📄 WindowStateService.cs
├── 📁 Helpers/
│ └── 📄 WindowStateHelper.cs
└── 📄 MainWindow.xaml.cs
Step 1: The Model WindowState
Every app needs a memory. This one’s called WindowState.
It’s a simple class that just holds the window’s coordinates, dimensions, scale, and whether it was
maximized.
Think of it as your app’s sticky note “Hey, last time I was 1200x800, bottom-right corner, and zoomed 125%.”
Step 2: The Service WindowStateService
The service does the actual saving and loading of your sticky note.
It uses ApplicationData.LocalSettings, which stores lightweight local
data that persists between sessions (even if the app crashes, which never happens, right?).
When you call:
Save(WindowState), it stores your window data locally.Load(), it reads it back when the app starts.
Step3: The helper WindowStateHelper
This is the real hero of the story.
It glues everything together, reading the current window size, saving it when you exit, and restoring it
next time.
Key things it does:
- Gets the AppWindow (the WinUI window manager).
- Uses
XamlRoot.RasterizationScaleto handle DPI scaling, so your window keeps the same physical size, even on different monitors. - Before saving, it temporarily restores the window if it’s maximized. That way, it saves the real size instead of the maximized size.
- When loading, it checks the display area bounds to ensure the window stays visible, so your window won’t appear half off-screen or trapped in monitor limbo.
.
Step4: Using It in MainWindow
In your main window, you only need two instructions:
if (Content is FrameworkElement content)
{
content.Loaded += (_, _) => WindowStateHelper.ApplySavedState(this);
}
Closed += (_, _) => WindowStateHelper.Save(this);
- The first part waits for the window content to load, then applies the saved state (if any).
- The second part saves the current state when the window closes.
Final Thoughts
Wouldn’t it be nice if the Windows App SDK just remembered your window
size and position by itself? You know, like every other framework that’s been alive since the dinosaurs of
desktop UI.
But no, here we are, writing our own WindowStateHelper just to make an
app remember it was once maximized.
On the bright side, now you have a clean, reusable solution, and a newfound respect for saving rectangles in memory.
Maybe one day, someone will add this feature natively. Until then, we’ll keep pretending this was fun to implement. (But deep down, we all wish this was just a property we could toggle instead of a weekend project.)