KARPACH

WEB DEVELOPER BLOG

Building a click-through shutdown timer overlay with WPF

Windows has had a shutdown timer built in forever: shutdown /s /t 3600. What it doesn’t have is any way to see how much time is left. You set it, a toast tells you once that Windows will sign you out, and after that you’re guessing. Most third-party shutdown timers fix that by giving you a window with a big countdown in it, and that window either gets buried under whatever you’re doing or covers part of it.

So I wrote Curfew: Shutdown Timer Overlay, a small .NET 9 WPF tray app that draws the countdown as bare digits in a screen corner. It has no window chrome, no background panel and no taskbar button: just outlined numbers that stay on top of everything and let the mouse click straight through them.

Countdown overlay in the bottom-right corner, above the taskbar

What it does, briefly:

  • Counts down to shutdown, restart, sleep, hibernate, log off, or just a notification
  • Starts in a duration (90m, 1h30m) or at a clock time (23:00)
  • Font, size, weight, fill and outline colour, outline width, and opacity are all adjustable
  • Any corner of any monitor, with margins, optionally clear of the taskbar
  • Blinks near the end (the last minute by default), and can hide itself when no countdown is running
  • An optional password that has to be entered before anyone can cancel, extend or exit
  • An optional route into exclusive-fullscreen games through RivaTuner Statistics Server

The rest of this post is an overview of how it’s put together.

A window that isn’t really there

The overlay is a WPF Window with WindowStyle="None", AllowsTransparency="True", a transparent background and SizeToContent, so it’s exactly as big as the digits. AllowsTransparency makes it a layered window (WS_EX_LAYERED) under the hood. That gets you invisibility. Getting it to ignore the mouse and stay out of the way takes three more extended styles, applied once the HWND exists:

protected override void OnSourceInitialized(EventArgs e)
{
    base.OnSourceInitialized(e);

    _hwnd = new WindowInteropHelper(this).Handle;

    var exStyle = NativeMethods.GetWindowLong(_hwnd, NativeMethods.GWL_EXSTYLE);
    exStyle |= NativeMethods.WS_EX_TRANSPARENT
             | NativeMethods.WS_EX_TOOLWINDOW
             | NativeMethods.WS_EX_NOACTIVATE;
    NativeMethods.SetWindowLong(_hwnd, NativeMethods.GWL_EXSTYLE, exStyle);
}
  • WS_EX_TRANSPARENT: hit-testing passes through, so clicks land on whatever is underneath
  • WS_EX_NOACTIVATE: the overlay never steals focus from the game or document you’re in
  • WS_EX_TOOLWINDOW: keeps it out of Alt+Tab and the taskbar

“Always on top” turned out to be less permanent than the name suggests. Full-screen apps and games regularly push their own window to the front of the z-order, and a Topmost="True" set once at startup loses that fight. The overlay re-stamps HWND_TOPMOST with SetWindowPos every two seconds on a background-priority DispatcherTimer. It’s cheap, and in practice every long-lived overlay ends up doing something like it.

Positioning skips WPF’s Left/Top entirely. Those are device-independent units, and lining a window up with the corner of a 150%-scaled monitor next to a 100% one means per-monitor DPI conversion. The overlay reads Screen.WorkingArea (or Bounds) in physical pixels, takes its own size from GetWindowRect, and calls SetWindowPos in physical pixels too, so no conversion happens anywhere. Because the window sizes to its content, it also repositions on SizeChanged. Otherwise going from 1:00:00 to 59:59 would leave a gap on the anchored side.

Digits you can read on any background

Text with no background box is unreadable somewhere. White digits vanish against a bright sky, black ones in a dark cave. The usual answer is an outline, and WPF’s TextBlock doesn’t have one.

OutlinedText is a small custom FrameworkElement that turns the string into glyph geometry and draws that with both a fill brush and a pen:

var formatted = new FormattedText(Text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
    typeface, FontSize, Brushes.Black, VisualTreeHelper.GetDpi(this).PixelsPerDip);

var geometry = formatted.BuildGeometry(new Point(0, 0));

// in OnRender
dc.PushTransform(new TranslateTransform(half, half));
dc.DrawGeometry(Fill, pen, geometry);

A pen is centred on the path, so half the stroke falls outside the glyph bounds. MeasureOverride pads the size by the stroke thickness and the render shifts by half of it, so the outline doesn’t get clipped at the edges. The pen uses round joins, which stops sharp glyph corners from turning into spikes at larger outline widths. The geometry is cached and rebuilt only when text, font or size change. The digits change once a second, so this barely matters, but it’s free.

The overlay is never hidden

This was the one real bug in the overlay, and it was a confusing one. “Hide when idle” is on by default, so the first version set Visibility.Hidden on startup and Visible when a countdown began. The digits never showed up.

A layered window hidden before its first render pass comes back with a stale, blank composited surface. The window was visible, topmost and correctly positioned, and completely empty. The fix is to leave the window shown at all times and fade the content instead:

public void SetVisible(bool visible)
{
    Digits.Opacity = visible ? 1.0 : 0.0;
}

An empty, click-through, fully transparent window costs nothing, so there’s no reason to ever hide it. The warning blink near the end works the same way: a DoubleAnimation on Opacity, not on visibility.

A countdown that doesn’t drift

The naïve countdown decrements a counter once a second on a timer. DispatcherTimer makes no promises about punctuality, though: a busy UI thread or a sleeping laptop delays ticks, and every late tick is time lost for good. Over an hour that adds up to the timer firing noticeably late.

CountdownService stores an absolute UTC target instead and recomputes the remaining time on every tick:

var left = _targetUtc - DateTime.UtcNow;

A missed or delayed tick fixes itself on the next one. The timer ticks every 200 ms rather than every second, so the displayed digit flips close to the real second boundary. “Add 10 minutes” just moves the target. Formatting rounds up, so the display reads 00:00:01 for the whole final second instead of showing 00:00:00 while there’s still time left.

Everything lives in the tray

A click-through overlay can’t be its own control surface, so the app lives in the system tray via WinForms' NotifyIcon. Right-click gives you quick presets when idle, and extend/cancel options while counting down. Double-click opens the settings window.

Tray menu when idle

Tray menu while a countdown is running

Using NotifyIcon (and Screen) means turning on UseWindowsForms next to UseWPF, which brings the usual pile of ambiguous Color, Brush, FontFamily, Size and Application references. This time the project removes the WinForms implicit usings in the .csproj and reaches for WinForms through aliases in the couple of files that need it:

<Using Remove="System.Drawing" />
<Using Remove="System.Windows.Forms" />
using Drawing = System.Drawing;
using WinForms = System.Windows.Forms;

A named mutex (Local\ShutdownTimer.SingleInstance) keeps a second copy from starting. Two instances would draw two sets of digits and fight over the in-game overlay slot. There’s also a small command line for desktop shortcuts and scheduled tasks:

Karpach.ShutdownTimer.exe --start 1h30m --action sleep
Karpach.ShutdownTimer.exe --at 23:00

Settings

Settings are a plain JSON file in %APPDATA%\ShutdownTimer\settings.json, written whenever something changes, and the settings window applies every change to the overlay immediately. There’s no Save button to forget.

Countdown tab

Appearance tab

Position tab

The action at zero is carried out mostly by delegating. Shutdown, restart and log off shell out to shutdown.exe, which already handles SeShutdownPrivilege and shows the standard Windows UI, so there’s no point reimplementing that around ExitWindowsEx. Sleep and hibernate call SetSuspendState from powrprof.dll directly, because shutdown.exe can’t sleep. If Windows refuses (hibernation disabled, say), the reason shows up as a tray balloon instead of the app quietly doing nothing.

Behaviour tab

The optional password is stored as a salted PBKDF2-SHA256 hash with 200,000 iterations, never in plain text, and compared with CryptographicOperations.FixedTimeEquals. It’s worth being honest about what it protects: it stops someone casually cancelling the timer from the tray, but it can’t stop the process being ended in Task Manager. For that, the person being timed needs a standard, non-admin Windows account.

Security tab

Showing over games

This is the part that depends on how the game presents its frames.

Borderless windowed is the default in most modern games, and it just works. Windows 10 and 11 promote a borderless window that covers the screen onto the same direct-presentation path that exclusive fullscreen uses, and the Desktop Window Manager still composites other windows on top. The overlay is an ordinary topmost window, so it simply draws over the game.

Exclusive fullscreen is a different story. The game owns the display and bypasses the DWM, so nothing the DWM composites can appear on top of it. No topmost flag, layered window or z-order trick gets around that. It’s what exclusive fullscreen means.

The only way over it is to draw into the game’s own frames by hooking IDXGISwapChain::Present (or the Vulkan/OpenGL equivalents). That’s how the Steam and Discord overlays work, and it looks exactly like what a cheat does. An unknown app injecting a DLL into a game protected by Easy Anti-Cheat, BattlEye or Vanguard is a good way to get someone banned, so Curfew deliberately doesn’t do that.

Instead, it borrows an overlay that is already trusted. RivaTuner Statistics Server (RTSS, bundled with MSI Afterburner) already hooks the present chain, is whitelisted by the major anti-cheat vendors, and publishes a documented shared-memory block, RTSSSharedMemoryV2, that lets other programs put text into its on-screen display. The client is plain MemoryMappedFile work:

  1. Open the mapping, check the RTSS signature and a minimum version
  2. Find an OSD slot whose owner string is ours, or the first free one
  3. Write the countdown text and our owner name, as fixed-size ANSI strings
  4. Bump the OSD frame counter, because RTSS only repaints when it changes

On RTSS 2.14 and later, writers also have to take a spin lock held in a dwBusy field of the header. That’s an Interlocked.CompareExchange on a raw pointer into the mapped view, released in a finally: a lock left set would freeze OSD updates for every RTSS client on the machine. The countdown colour goes along as RTSS markup (<C=RRGGBB>) so the in-game text matches the desktop one, and the write is skipped whenever the text hasn’t changed since the last one. The overlay ticks at 5 Hz, but the digits only change once a second.

In-game tab

A few decisions around it:

  • It fails quietly when it should. RTSS not running is the normal case and produces no message. Real problems do produce one, the most common being an elevation mismatch: RTSS usually runs as administrator, and an unelevated app can’t open its mapping for writing. That gets reported once as a tray balloon, and the desktop overlay keeps working regardless.
  • It never installs anything by itself. If RTSS isn’t found, the settings window offers an Install RTSS… button that runs winget install Guru3D.RTSS in a visible console, so the user sees the licence prompt and the UAC prompt, or opens the download page if winget is missing.
  • It’s untested against a live RTSS. The client is written to the layout in the RTSS SDK header (RTSSSharedMemory.h) and has never run against a real RTSS instance, because RTSS isn’t installed on the machine it was developed on. Until that happens, I’d call the in-game route best-effort.

Microsoft Store packaging

Distribution is an MSIX in the Microsoft Store. Build-Msix.ps1 publishes a self-contained build and packs it with makeappx, unsigned, since the Store signs submitted packages itself. A GitHub Actions workflow runs on every push to main. It takes major.minor from <Version> in the .csproj, sets the build number to the latest matching git tag plus one, and publishes a GitHub release with the MSIX attached. The Store requires versions to only go up and the fourth part to be 0, and a monotonic tag-derived build number meets both rules without anyone having to think about it.

The Store version has a 14-day free trial. The trial is configured in Partner Center, and the Store keeps track of the dates, so LicenseService only reads StoreContext.GetAppLicenseAsync() and reports back. A few rules around it:

  • Unpackaged builds are always full. Anything built from source has no package identity and no Store license to read. GetCurrentPackageFullName returning APPMODEL_ERROR_NO_PACKAGE detects that without exceptions.
  • A Store error fails open. A Store service outage must never lock out someone who paid.
  • An expired trial blocks new countdowns only. A countdown that is already running still finishes or can be cancelled. Locking someone’s shutdown timer halfway through would be the worst possible moment to ask for money.
  • The purchase dialog needs a window. StoreContext on Win32 has to be given an HWND via InitializeWithWindow, and the overlay is click-through and never activates, so it’s useless as an owner. When the purchase starts from the tray, a 1×1 off-screen helper window is created for the dialog and closed afterwards.

A CURFEW_SIMULATE_LICENSE=trial:3|expired|full environment variable, compiled into Debug builds only, drives the trial UI without a Store build, because the real flow can only be tested from a Store flight.

Wrapping up

Most of the app is ordinary WPF. The interesting parts were all about how Windows composites windows: a layered window that goes blank if you hide it too early, “topmost” that doesn’t stay topmost, DPI units that don’t line up with physical corners, and a class of games where no window can appear on top at all. For those games, borrowing RTSS’s overlay rather than writing an injector was an easy call. The countdown is useful, but it isn’t worth risking anyone’s game account.

Curfew is on the Microsoft Store with a 14-day free trial, then a one-time purchase. No subscription.

Posted on September 23, 2026 by

Building an envelope printing app with WPF, GDI+ and the Microsoft Store

The standard answer to “how do I print an address on an envelope” is Microsoft Word’s envelope wizard. I don’t have Word, and I wasn’t about to start paying for a Microsoft 365 subscription to put two addresses on a piece of paper a few times a month. The free alternatives I found were either web tools that want you to hand over an address list, or utilities with a fixed layout you can’t move.

So I wrote my own: Mailwright - Envelope Address Printer, a small .NET 8 WPF app that puts two draggable address blocks on a canvas shaped like a real envelope and prints exactly what you see. No Office subscription, and rather more control than the Word wizard offers — in Word the address boxes sit where Word decides, and font changes happen in a dialog you can’t see the result of. Here you drag each block to where you want it on a to-scale envelope, set the font family, size and color per block, and the canvas is the preview.

Mailwright - Envelope Address Printer main window

What it does, briefly:

  • Recipient and return address blocks you drag around a live canvas — the canvas is the envelope, at scale
  • Four envelope sizes: No. 10, C4, C5, DL
  • Per-block font family, size and color (each block is configured independently)
  • Optional sender logo image next to the return address
  • Return address and the last 10 recipients persist between runs
  • Print preview before committing an envelope to the printer

The rest of this post is about the parts that didn’t work the first time.

One project, two UI frameworks

The app is WPF, but WPF has no printer-selection dialog worth using and no print preview at all. System.Windows.Controls.PrintDialog gives you a printer picker but the actual page rendering means building a DocumentPaginator over WPF visuals, and there is no PrintPreviewDialog equivalent in the box. WinForms has both, plus System.Drawing.Printing.PrintDocument, which is a far more direct way to say “draw this string at this point on the page.”

So the .csproj enables both:

<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>

That compiles, and then every file in the project starts failing with CS0104: ambiguous reference. Both frameworks contribute implicit global usings, so Application, FontFamily, Point, UserControl, MouseEventArgs and Color all resolve to two different types at once.

The fix is a GlobalUsings.cs that picks a winner project-wide:

global using Application    = System.Windows.Application;
global using FontFamily     = System.Windows.Media.FontFamily;
global using MouseEventArgs = System.Windows.Input.MouseEventArgs;
global using Point          = System.Windows.Point;
global using UserControl    = System.Windows.Controls.UserControl;

WPF wins by default, and the one file that genuinely needs WinForms — the print service — reaches for it through a local alias instead:

using WinForms = System.Windows.Forms;

using var dlg = new WinForms.PrintDialog { Document = doc };

Color is the nastiest of the bunch, because System.Drawing stays an implicit global using for the whole project. Any file that also imports System.Windows.Media has to fully qualify it:

var color = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(hex)!;

It looks ugly, but aliasing Color globally would have broken the GDI+ side. Fully qualifying in the three files that care was the smaller evil.

Two coordinate systems that must agree

The on-screen canvas is WPF, so it measures in device-independent pixels: 96 DIP to the inch. The printed page is GDI+ System.Drawing.Printing, which by default measures in hundredths of an inch. A No. 10 envelope is 9.5″ × 4.125″, which is 912 × 396 DIP on screen and 950 × 412 on paper.

The temptation is to store block positions in one unit and convert. That falls apart the moment the user switches envelope size — a block sitting at “x = 400 pixels” is in a sensible place on a C4 and hanging off the edge of a DL.

Positions are therefore stored as fractions of the envelope, 0 to 1, and each renderer multiplies by its own page dimensions. Dropping a block on the canvas converts pixels down to a fraction:

[RelayCommand]
private void ToDragCompleted(Point p)
{
    PrintSettings.ToLeftFraction = CanvasWidth  > 0 ? p.X / CanvasWidth  : AppConstants.AddressBlockPositions.ToLeftFraction;
    PrintSettings.ToTopFraction  = CanvasHeight > 0 ? p.Y / CanvasHeight : AppConstants.AddressBlockPositions.ToTopFraction;
    _addressService.SavePrintSettings(PrintSettings);
}

and the print path multiplies the same fraction back up against GDI+ units, never touching DIPs at all:

float pageW = (float)AppConstants.InchesToGdiUnits(widthIn);   // hundredths of an inch
float pageH = (float)AppConstants.InchesToGdiUnits(heightIn);

DrawAddress(g, recipientText, toFont, toBrush,
    pageW * (float)settings.ToLeftFraction,
    pageH * (float)settings.ToTopFraction,
    pageW * (float)AppConstants.AddressBlockDimensions.ToPrintBlockWidthFraction,
    pageH * (float)AppConstants.AddressBlockDimensions.ToPrintBlockHeightFraction);

Both conversions live in a single AppConstants class, which is the only place 96.0 and 100 appear. Envelope switching then costs nothing: recompute the canvas size, re-multiply the fractions, done.

One thing that is deliberately not a fraction: font size. Points are absolute, so 14pt on screen and 14pt on paper are the same physical height, and the preview stays honest.

Getting the printer to admit it knows what an envelope is

This was the longest detour. PrintDocument lets you set DefaultPageSettings.PaperSize to a custom PaperSize with any dimensions you like, and that mostly works — the page comes out the right size. What it does not do is tell the printer driver “this is an envelope,” so the driver keeps its letter-tray settings, reports a PrintableArea for letter paper, and some drivers helpfully scale or reject the job.

The right move is to ask the driver for its own PaperSize entry matching the correct PaperKind. That has two wrinkles.

First, System.Drawing.Printing.PaperKind only has a named member for Number10Envelope. C4, C5 and DL exist in the underlying Win32 DMPAPER_* constants but not as friendly enum names, so they get cast in by value:

public static PaperKind GetPaperKind(EnvelopeSize size) =>
    size switch
    {
        EnvelopeSize.No10 => PaperKind.Number10Envelope, // DMPAPER_ENV_10 = 20
        EnvelopeSize.C4   => (PaperKind)30,              // DMPAPER_ENV_C4 = 30
        EnvelopeSize.C5   => (PaperKind)28,              // DMPAPER_ENV_C5 = 28
        EnvelopeSize.DL   => (PaperKind)27,              // DMPAPER_ENV_DL = 27
        _                 => PaperKind.Number10Envelope
    };

Second, you can’t resolve the paper size when you build the document, because at that point the user hasn’t picked a printer yet. PrintDocument raises QueryPageSettings immediately before each page, with the actual selected printer’s settings attached — that’s the hook:

doc.QueryPageSettings += (_, qe) =>
{
    var nativeSize = qe.PageSettings.PrinterSettings
        .PaperSizes
        .Cast<PaperSize>()
        .FirstOrDefault(ps => ps.Kind == paperKind)
        ?? customSize;

    qe.PageSettings.PaperSize = nativeSize;
    qe.PageSettings.Landscape = true;
    qe.PageSettings.Margins   = new Margins(0, 0, 0, 0);
};

If the driver doesn’t list that kind — plenty of PDF writers don’t — it falls back to a custom PaperSize built from the known dimensions. Note that the custom size is constructed with height and width swapped relative to the layout values, because PaperSize describes the sheet in portrait and Landscape = true rotates it.

The last piece is a decision not to use what the driver reports. PrintPage lays out against the nominal envelope dimensions, not e.Graphics.VisibleClipBounds or PageSettings.PrintableArea. Printable area varies by driver and by hardware margins, and honoring it means the same envelope prints differently on two printers — while the on-screen preview shows only one of them. Laying out against the true physical envelope keeps WYSIWYG intact; the cost is that an address dragged into the outer few millimeters may clip on a printer with large hardware margins.

The preview dialog has a Print button, and it doesn’t tell you

The app has a five-print free trial, and the counter increments after a successful print. PrintPreviewDialog quietly broke that: its toolbar includes a printer icon that calls PrintDocument.Print() directly. No event, no return value, no notification to the calling code. Free unlimited printing, one click away.

There is no property to hide it, so the toolbar gets walked and the button is switched off by name:

foreach (Control control in dlg.Controls)
{
    if (control is ToolStrip toolStrip)
    {
        foreach (ToolStripItem item in toolStrip.Items)
        {
            if (item.Name == "printToolStripButton")
            {
                item.Visible = false;
                break;
            }

            // Fallback check if the name differs in some .NET versions
            if (item.ToolTipText == "Print")
            {
                item.Visible = false;
                break;
            }
        }
    }
}

Reaching into another control’s private layout by string is exactly as fragile as it looks, hence the tooltip fallback. The result is the preview window below — zoom and page-layout buttons, no printer icon.

Print preview window

The same bug had a mirror image on the real print path. IPrintService.Print originally returned void, so cancelling the printer dialog still burned a trial print. It now returns whether the dialog was accepted:

bool isPrinted = _printService.Print(ToText, FromText, PrintSettings);

if (!isUnlocked && isPrinted)
{
    _licensingService.IncrementPrintCount();
    await UpdateLicensingStatusAsync();
}

Parenting a WinForms dialog to a WPF window

WinForms.PrintDialog.ShowDialog() with no argument shows an unowned dialog: it can end up behind the main window, and Alt+Tab treats it as a separate top-level thing. It wants an IWin32Window, which WPF windows are not. You get the HWND from WindowInteropHelper and wrap it in four lines:

private static WinForms.IWin32Window? GetOwnerHandle()
{
    var mainWindow = Application.Current?.MainWindow;
    if (mainWindow is null) return null;
    var handle = new WindowInteropHelper(mainWindow).Handle;
    return handle == IntPtr.Zero ? null : new NativeWindow(handle);
}

private sealed class NativeWindow(IntPtr handle) : WinForms.IWin32Window
{
    public IntPtr Handle { get; } = handle;
}

The handle == IntPtr.Zero check matters — the HWND doesn’t exist until the window is sourced, so calling this too early in startup silently gives you an unowned dialog again.

Store add-on licensing: the key isn’t the key

The full version is a durable in-app purchase, checked through Windows.Services.Store. Two things bit me here.

StoreContext is a WinRT API designed for UWP, where there’s an implicit window. On Win32 it has no idea which window to attach its purchase UI to, and calls fail or hang until you tell it:

var storeContext = StoreContext.GetDefault();
var hwnd = new WindowInteropHelper(Application.Current.MainWindow).Handle;
InitializeWithWindow.Initialize(storeContext, hwnd);

Which means the license check cannot run during OnStartup before the window exists. It’s kicked off after Show() instead:

MainWindow = mainWindow;
mainWindow.Show();

// Must run after MainWindow is assigned so the Store license check
// can associate with a window handle.
_ = mainViewModel.InitializeLicensingStatusAsync();

The second one only shows up once someone has actually bought the add-on. StoreAppLicense.AddOnLicenses is a dictionary, and the obvious code is:

license.AddOnLicenses.TryGetValue(FullVersionStoreId, out var addOnLicense)

That never matches. The dictionary is keyed by <StoreId>/<Sku> — "9MTPB8D2TFGH/0010", not "9MTPB8D2TFGH". So a paid-up license reads as “not purchased” and the app keeps showing the trial limit, with no error from the API anywhere — just an absent key. Matching on the prefix fixes it:

private static StoreLicense? FindFullVersionLicense(StoreAppLicense license)
{
    foreach (var kvp in license.AddOnLicenses)
    {
        if (kvp.Key == FullVersionStoreId || kvp.Key.StartsWith(FullVersionStoreId + "/", StringComparison.Ordinal))
        {
            return kvp.Value;
        }
    }

    return null;
}

Debugging this is awkward because Store APIs only work when the app is packaged and installed, which is not how you run it under F5. Detecting that is itself an exception-driven check — Windows.ApplicationModel.Package.Current throws InvalidOperationException when unpackaged rather than returning null:

private static bool IsPackaged()
{
    try
    {
        return Windows.ApplicationModel.Package.Current != null && Windows.ApplicationModel.Package.Current.Id != null;
    }
    catch (InvalidOperationException)
    {
        return false;
    }
}

Unpackaged runs fall back to a local flag in the database so the UI is still testable. That’s a development bypass, not an entitlement check, and it’s worth being clear-eyed about which one you’ve written.

MSIX signing: the certificate subject is not a label

The CI build produces a signed MSIX. My first attempt created a self-signed certificate with a friendly-looking subject:

New-SelfSignedCertificate -Type CodeSigningCert -Subject "CN=Karpach.EnvelopPrinter" ...

signtool was happy. Installation failed with 0x8007000B. The certificate subject must match the Publisher attribute in AppxManifest.xml character for character — and once you reserve a name in Partner Center, that value becomes CN=6884325E-1F8A-4326-8D57-2AFC390B7FD6, not anything human-readable. The build now reads the publisher out of the manifest instead of hardcoding it:

[xml]$manifest = Get-Content "msix-publish\AppxManifest.xml"
$publisher = $manifest.Package.Identity.Publisher

$cert = New-SelfSignedCertificate -Type CodeSigningCert -Subject $publisher `
  -FriendlyName "Envelope Printer Test Certificate" `
  -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.3") `
  -NotAfter (Get-Date).AddYears(5)

It also deletes any cached .pfx first, so a manifest change can’t leave a stale certificate signing packages with the wrong subject.

Versioning had a related snag. Locally the version comes from git tags via MinVer, which produces things like 1.1.3-alpha.0.5 on untagged commits. The Store requires strictly Major.Minor.Build.0 with a fourth part of zero. CI therefore skips MinVer entirely and derives the version from the run number, which is monotonic by construction:

- name: Build solution
  run: dotnet build --configuration Release --no-restore /p:MinVerSkip=true /p:Version=${{ env.DISPLAY_VERSION }} /p:FileVersion=${{ env.MSIX_VERSION }} /p:AssemblyVersion=${{ env.MSIX_VERSION }}

with DISPLAY_VERSION = 1.1.<run_number> and MSIX_VERSION = 1.1.<run_number>.0.

Schema changes without EF migrations

Settings live in SQLite at %AppData%\Karpach.EnvelopPrinter\app.db via EF Core 8. The first release shipped with Database.EnsureCreated(), which is convenient and a dead end: it creates the schema once and then never touches it again. Every column added since — the trial counter, the font colors, the logo position — would simply be missing on an existing user’s database, and EnsureCreated() reports no problem at all. You find out when a query fails.

Since users' addresses live in that file, dropping and recreating it wasn’t acceptable. EnsureDatabase() now probes for each column and adds it if absent:

try
{
    using var cmd = conn.CreateCommand();
    cmd.CommandText = "SELECT FromFontColor FROM PrintSettings LIMIT 1";
    cmd.ExecuteNonQuery();
}
catch
{
    using var cmd = conn.CreateCommand();
    cmd.CommandText = "ALTER TABLE PrintSettings ADD COLUMN FromFontColor TEXT NOT NULL DEFAULT '#000000'";
    cmd.ExecuteNonQuery();
}

Exception-driven, repeated per column, and honestly it should have been proper EF migrations from day one. It ends with a single SELECT naming every expected column; if that throws, the schema has drifted beyond repair and the file gets deleted and rebuilt.

Deleting it has its own trap. Microsoft.Data.Sqlite pools connections, so the file handle outlives the DbContext and File.Delete fails with a sharing violation:

SqliteConnection.ClearAllPools();
if (File.Exists(dbPath))
    File.Delete(dbPath);

Small things that turned out to matter

Drag versus click on the same control. The address blocks are both draggable and click-to-edit. Treating MouseLeftButtonUp as a click means a 2-pixel wobble while dragging drops you into edit mode. A 4-pixel threshold separates the two intents:

if (!_isDragging && (Math.Abs(dx) > DragThreshold || Math.Abs(dy) > DragThreshold))
    _isDragging = true;

On mouse-up, _isDragging decides whether to persist a position or focus the text box.

The color palette is free. Rather than build a color picker, the dropdown reflects over System.Windows.Media.Colors and turns each named static property into a swatch with a #RRGGBB string. The hex string is what gets stored, which is also what GDI+ accepts via ColorTranslator.FromHtml — one representation, both renderers.

Address settings dialog

Logos get re-encoded on import. The user picks any image; it’s decoded, capped at 1000px on the long edge using BitmapImage.DecodePixelWidth (which downsamples during decode rather than after), and re-saved as PNG. Otherwise a 12MP phone photo ends up permanently in AppData for a box that renders at under an inch.

Wrapping up

Roughly speaking: the WPF/WinForms interop and the coordinate math were tedious but predictable, while the genuinely expensive bugs — the preview dialog’s hidden print button, the AddOnLicenses key format, the certificate subject mismatch — were all cases where an API failed silently and did something plausible instead of complaining. Printing and Store licensing are both areas where “it returned without throwing” means very little.

The app is on the Microsoft Store: five free prints to try it, then a one-time add-on unlocks unlimited printing. No subscription, and no Office required.

Posted on August 20, 2026 by

Getting Started with Poetry

I don’t have much experience with Python. A few years ago, I created a few fairly simple lead collector websites using Flask and that was pretty much it.

Then a few weeks ago I bought couple TP-Link smart light bulbs and quickly realized that Home Assistant’s built-in functionality does not serve my needs. I had to modify python-kasa Python library.

The library is using a poetry dependency management tool. It took me a few hours to understand the basics of it, so below I will summarize how to get started with it. The below guide is for Windows.

Prerequisites: Make sure you have Python installed and you checked during the installation checkbox for updating the path environment variable. This will enable Python and Pip to work from any Windows folder.

First, you need to install poetry. Run the following in Windows PowerShell:

pip install poetry

Then you need to initialize it:

poetry install

I assume you want to modify the source code, so open Visual Studio Code at the root of the project. Open any Python file to trigger an installation of the Python extension.

Then in the VS Code terminal (PowerShell) run:

poetry shell

In VS Code command prompt (Shift+Ctrl+p), type “Python: Select Interpreter”. Select the line which refers to Poetry at the right.

You are all set. Optionally you can open the Testing sidebar and configure the Python testing framework. Then run tests to confirm that your dev environment is fully functional.

Posted on July 7, 2023 by