using System; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Win32; namespace M365IsoDownloaderSetup { internal static unsafe class SetupNative { public const uint WS_OVERLAPPED = 0x00000000; public const uint WS_CAPTION = 0x00C00000; public const uint WS_SYSMENU = 0x00080000; public const uint WS_MINIMIZEBOX = 0x00020000; public const uint CS_HREDRAW = 0x0002; public const uint CS_VREDRAW = 0x0001; public const uint WM_DESTROY = 0x0002; public const uint WM_PAINT = 0x000F; public const uint WM_CLOSE = 0x0010; public const uint WM_ERASEBKGND = 0x0014; public const uint WM_SETCURSOR = 0x0020; public const uint WM_MOUSEMOVE = 0x0200; public const uint WM_LBUTTONDOWN = 0x0201; public const uint WM_LBUTTONUP = 0x0202; public const uint WM_MOUSELEAVE = 0x02A3; public const uint WM_DPICHANGED = 0x02E0; public const int SW_SHOW = 5; public const int IDC_ARROW = 32512; public const int IDC_HAND = 32649; public const uint SRCCOPY = 0x00CC0020; public const uint MB_OK = 0x00000000; public const uint MB_YESNO = 0x00000004; public const uint MB_ICONINFORMATION = 0x00000040; public const uint MB_ICONQUESTION = 0x00000020; public const uint MB_ICONERROR = 0x00000010; public const int IDYES = 6; [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; } [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; } [StructLayout(LayoutKind.Sequential)] public struct MSG { public IntPtr hwnd; public uint message; public nuint wParam; public nint lParam; public uint time; public POINT pt; } [StructLayout(LayoutKind.Sequential)] public struct PAINTSTRUCT { public IntPtr hdc; public int fErase; public RECT rcPaint; public int fRestore; public int fIncUpdate; public fixed byte rgbReserved[32]; } [StructLayout(LayoutKind.Sequential)] public struct TRACKMOUSEEVENT { public uint cbSize; public uint dwFlags; public IntPtr hwndTrack; public uint dwHoverTime; } [StructLayout(LayoutKind.Sequential)] public struct WNDCLASSEXW { public uint cbSize; public uint style; public delegate* unmanaged[Stdcall] lpfnWndProc; public int cbClsExtra; public int cbWndExtra; public IntPtr hInstance; public IntPtr hIcon; public IntPtr hCursor; public IntPtr hbrBackground; public char* lpszMenuName; public char* lpszClassName; public IntPtr hIconSm; } [StructLayout(LayoutKind.Sequential)] public struct BITMAPINFOHEADER { public uint biSize; public int biWidth; public int biHeight; public ushort biPlanes; public ushort biBitCount; public uint biCompression; public uint biSizeImage; public int biXPelsPerMeter; public int biYPelsPerMeter; public uint biClrUsed; public uint biClrImportant; } [StructLayout(LayoutKind.Sequential)] public struct RectF { public float X, Y, Width, Height; public RectF(float x, float y, float w, float h) { X = x; Y = y; Width = w; Height = h; } public bool Contains(float px, float py) => px >= X && px <= X + Width && py >= Y && py <= Y + Height; } [StructLayout(LayoutKind.Sequential)] public struct GdiplusStartupInput { public uint GdiplusVersion; public IntPtr DebugEventCallback; public int SuppressBackgroundThread; public int SuppressExternalCodecs; } [DllImport("kernel32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] public static extern IntPtr GetModuleHandleW(char* lpModuleName); [DllImport("user32.dll", ExactSpelling = true)] public static extern ushort RegisterClassExW(ref WNDCLASSEXW lpwcx); [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] public static extern IntPtr CreateWindowExW( uint dwExStyle, char* lpClassName, char* lpWindowName, uint dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam); [DllImport("user32.dll", ExactSpelling = true)] public static extern int ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll", ExactSpelling = true)] public static extern int UpdateWindow(IntPtr hWnd); [DllImport("user32.dll", ExactSpelling = true)] public static extern int DestroyWindow(IntPtr hWnd); [DllImport("user32.dll", ExactSpelling = true)] public static extern void PostQuitMessage(int nExitCode); [DllImport("user32.dll", ExactSpelling = true)] public static extern nint DefWindowProcW(IntPtr hWnd, uint msg, nuint wParam, nint lParam); [DllImport("user32.dll", ExactSpelling = true)] public static extern int GetMessageW(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax); [DllImport("user32.dll", ExactSpelling = true)] public static extern int TranslateMessage(ref MSG lpMsg); [DllImport("user32.dll", ExactSpelling = true)] public static extern nint DispatchMessageW(ref MSG lpMsg); [DllImport("user32.dll", ExactSpelling = true)] public static extern int InvalidateRect(IntPtr hWnd, IntPtr lpRect, int bErase); [DllImport("user32.dll", ExactSpelling = true)] public static extern int GetClientRect(IntPtr hWnd, out RECT lpRect); [DllImport("user32.dll", ExactSpelling = true)] public static extern IntPtr BeginPaint(IntPtr hWnd, out PAINTSTRUCT lpPaint); [DllImport("user32.dll", ExactSpelling = true)] public static extern int EndPaint(IntPtr hWnd, ref PAINTSTRUCT lpPaint); [DllImport("user32.dll", ExactSpelling = true)] public static extern IntPtr LoadCursorW(IntPtr hInstance, IntPtr lpCursorName); [DllImport("user32.dll", ExactSpelling = true)] public static extern IntPtr SetCursor(IntPtr hCursor); [DllImport("user32.dll", ExactSpelling = true)] public static extern IntPtr LoadIconW(IntPtr hInstance, IntPtr lpIconName); [DllImport("user32.dll", ExactSpelling = true)] public static extern uint GetDpiForWindow(IntPtr hwnd); [DllImport("user32.dll", ExactSpelling = true)] public static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); [DllImport("user32.dll", ExactSpelling = true)] public static extern int GetSystemMetrics(int nIndex); [DllImport("user32.dll", ExactSpelling = true)] public static extern int TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack); [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] public static extern int MessageBoxW(IntPtr hWnd, string lpText, string lpCaption, uint uType); [DllImport("dwmapi.dll", ExactSpelling = true)] public static extern int DwmSetWindowAttribute(IntPtr hwnd, uint dwAttribute, void* pvAttribute, uint cbAttribute); [DllImport("gdi32.dll", ExactSpelling = true)] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("gdi32.dll", ExactSpelling = true)] public static extern int DeleteDC(IntPtr hdc); [DllImport("gdi32.dll", ExactSpelling = true)] public static extern IntPtr CreateDIBSection(IntPtr hdc, ref BITMAPINFOHEADER pbmi, uint usage, out IntPtr ppvBits, IntPtr hSection, uint offset); [DllImport("gdi32.dll", ExactSpelling = true)] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr h); [DllImport("gdi32.dll", ExactSpelling = true)] public static extern int DeleteObject(IntPtr ho); [DllImport("gdi32.dll", ExactSpelling = true)] public static extern int BitBlt(IntPtr hdc, int x, int y, int cx, int cy, IntPtr hdcSrc, int x1, int y1, uint rop); [DllImport("shell32.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] public static extern IntPtr ShellExecuteW(IntPtr hwnd, string lpOperation, string lpFile, string? lpParameters, string? lpDirectory, int nShowCmd); [DllImport("ole32.dll", ExactSpelling = true)] public static extern int CoInitializeEx(IntPtr pvReserved, uint dwCoInit); [DllImport("ole32.dll", ExactSpelling = true)] public static extern void CoUninitialize(); [DllImport("ole32.dll", ExactSpelling = true)] public static extern int CoCreateInstance(ref Guid rclsid, IntPtr pUnkOuter, uint dwClsContext, ref Guid riid, out void* ppv); // GDI+ [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdiplusStartup(out nuint token, ref GdiplusStartupInput input, IntPtr output); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern void GdiplusShutdown(nuint token); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipCreateFromHDC(IntPtr hdc, out IntPtr graphics); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipDeleteGraphics(IntPtr graphics); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipSetSmoothingMode(IntPtr graphics, int smoothingMode); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipSetPixelOffsetMode(IntPtr graphics, int pixelOffsetMode); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipSetTextRenderingHint(IntPtr graphics, int mode); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipGraphicsClear(IntPtr graphics, uint color); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipCreateSolidFill(uint color, out IntPtr brush); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipDeleteBrush(IntPtr brush); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipCreatePen1(uint color, float width, int unit, out IntPtr pen); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipSetPenLineCap197819(IntPtr pen, int startCap, int endCap, int dashCap); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipSetPenLineJoin(IntPtr pen, int lineJoin); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipDeletePen(IntPtr pen); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipDrawLine(IntPtr graphics, IntPtr pen, float x1, float y1, float x2, float y2); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipFillRectangle(IntPtr graphics, IntPtr brush, float x, float y, float width, float height); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipCreatePath(int brushMode, out IntPtr path); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipDeletePath(IntPtr path); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipAddPathArc(IntPtr path, float x, float y, float width, float height, float startAngle, float sweepAngle); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipClosePathFigure(IntPtr path); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipFillPath(IntPtr graphics, IntPtr brush, IntPtr path); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipDrawPath(IntPtr graphics, IntPtr pen, IntPtr path); [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] public static extern int GdipCreateFontFamilyFromName(string name, IntPtr fontCollection, out IntPtr fontFamily); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipDeleteFontFamily(IntPtr fontFamily); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipCreateFont(IntPtr fontFamily, float emSize, int style, int unit, out IntPtr font); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipDeleteFont(IntPtr font); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipCreateStringFormat(int formatAttributes, int language, out IntPtr format); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipDeleteStringFormat(IntPtr format); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipSetStringFormatAlign(IntPtr format, int align); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipSetStringFormatLineAlign(IntPtr format, int align); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipSetStringFormatTrimming(IntPtr format, int trimming); [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] public static extern int GdipDrawString(IntPtr graphics, string str, int length, IntPtr font, ref RectF layoutRect, IntPtr stringFormat, IntPtr brush); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipCreateBitmapFromScan0(int width, int height, int stride, int format, IntPtr scan0, out IntPtr bitmap); [DllImport("gdiplus.dll", ExactSpelling = true)] public static extern int GdipDisposeImage(IntPtr image); [DllImport("gdiplus.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] public static extern int GdipSaveImageToFile(IntPtr image, string filename, ref Guid clsidEncoder, IntPtr encoderParams); // NativeAOT COM wrapper for creating standard Windows .lnk shortcuts public static void CreateShortcut(string shortcutPath, string targetExePath, string workingDir, string description) { string? parentDir = Path.GetDirectoryName(shortcutPath); if (!string.IsNullOrEmpty(parentDir) && !Directory.Exists(parentDir)) { Directory.CreateDirectory(parentDir); } Guid clsidShellLink = new Guid("00021401-0000-0000-C000-000000000046"); Guid iidShellLinkW = new Guid("000214F9-0000-0000-C000-000000000046"); Guid iidPersistFile = new Guid("0000010b-0000-0000-C000-000000000046"); void* pShellLink = null; if (CoCreateInstance(ref clsidShellLink, IntPtr.Zero, 1 /* CLSCTX_INPROC_SERVER */, ref iidShellLinkW, out pShellLink) < 0 || pShellLink == null) { return; } try { void** vtbl = *(void***)pShellLink; var setDescription = (delegate* unmanaged[Stdcall])vtbl[7]; var setWorkingDir = (delegate* unmanaged[Stdcall])vtbl[9]; var setIconLocation = (delegate* unmanaged[Stdcall])vtbl[17]; var setPath = (delegate* unmanaged[Stdcall])vtbl[20]; var queryInterface = (delegate* unmanaged[Stdcall])vtbl[0]; fixed (char* pTarget = targetExePath) fixed (char* pWorkDir = workingDir) fixed (char* pDesc = description) { setPath(pShellLink, pTarget); setWorkingDir(pShellLink, pWorkDir); setDescription(pShellLink, pDesc); setIconLocation(pShellLink, pTarget, 0); } void* pPersistFile = null; if (queryInterface(pShellLink, &iidPersistFile, &pPersistFile) >= 0 && pPersistFile != null) { try { void** pfVtbl = *(void***)pPersistFile; var save = (delegate* unmanaged[Stdcall])pfVtbl[6]; fixed (char* pLnk = shortcutPath) { save(pPersistFile, pLnk, 1); } } finally { var releasePf = (delegate* unmanaged[Stdcall])(*(void***)pPersistFile)[2]; releasePf(pPersistFile); } } } finally { var releaseSl = (delegate* unmanaged[Stdcall])(*(void***)pShellLink)[2]; releaseSl(pShellLink); } } } internal sealed unsafe class InstallerWindow { public static InstallerWindow? Instance; private const string AppDisplayName = "Microsoft 365 Offline Image Downloader"; private const string AppVersion = "1.0.0"; private const string UninstallRegSubKey = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\M365IsoDownloader"; private IntPtr _hwnd; private IntPtr _fontFamily; private IntPtr _cursorArrow; private IntPtr _cursorHand; private float _dpiScale = 1.0f; private readonly string _installDir; private bool _createStartMenuShortcut = true; private bool _createDesktopShortcut = true; private bool _launchAfterInstall = true; private bool _installedSuccessfully; private string _statusMessage = "Ready to install to your user profile (no administrator rights required)."; private SetupNative.RectF _cbStartMenuRect; private SetupNative.RectF _cbDesktopRect; private SetupNative.RectF _cbLaunchRect; private SetupNative.RectF _primaryBtnRect; private SetupNative.RectF _cancelBtnRect; private int _hoveredId = -1; private int _pressedId = -1; private bool _mouseDown; private bool _trackingMouse; public InstallerWindow() { string localPrograms = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs"); _installDir = Path.Combine(localPrograms, "M365IsoDownloader"); } private void EnsureFont() { if (_fontFamily == IntPtr.Zero) { if (SetupNative.GdipCreateFontFamilyFromName("Segoe UI", IntPtr.Zero, out _fontFamily) != 0 || _fontFamily == IntPtr.Zero) { SetupNative.GdipCreateFontFamilyFromName("Arial", IntPtr.Zero, out _fontFamily); } } } public int RunPreviewPng(string outPath) { EnsureFont(); int w = 560, h = 410; IntPtr memDc = SetupNative.CreateCompatibleDC(IntPtr.Zero); SetupNative.BITMAPINFOHEADER bmi = new SetupNative.BITMAPINFOHEADER { biSize = (uint)sizeof(SetupNative.BITMAPINFOHEADER), biWidth = w, biHeight = -h, biPlanes = 1, biBitCount = 32 }; IntPtr hDib = SetupNative.CreateDIBSection(memDc, ref bmi, 0, out IntPtr bits, IntPtr.Zero, 0); IntPtr oldBmp = SetupNative.SelectObject(memDc, hDib); if (SetupNative.GdipCreateFromHDC(memDc, out IntPtr g) == 0 && g != IntPtr.Zero) { Paint(g, w, h, 1.0f); SetupNative.GdipDeleteGraphics(g); } if (SetupNative.GdipCreateBitmapFromScan0(w, h, w * 4, 0x00022009, bits, out IntPtr gdipBmp) == 0 && gdipBmp != IntPtr.Zero) { Guid pngEncoder = new Guid("557CF406-1A04-11D3-9A73-0000F81EF32E"); string? dir = Path.GetDirectoryName(outPath); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) Directory.CreateDirectory(dir); SetupNative.GdipSaveImageToFile(gdipBmp, outPath, ref pngEncoder, IntPtr.Zero); SetupNative.GdipDisposeImage(gdipBmp); } SetupNative.SelectObject(memDc, oldBmp); SetupNative.DeleteObject(hDib); SetupNative.DeleteDC(memDc); return 0; } public static int RunUninstall(bool silent) { string localPrograms = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs"); string installDir = Path.Combine(localPrograms, "M365IsoDownloader"); if (!silent) { int confirm = SetupNative.MessageBoxW( IntPtr.Zero, "Uninstall Microsoft 365 Offline Image Downloader from your computer?\n\n(Any downloaded .img files in your Downloads folder will be kept.)", "Uninstall Microsoft 365 Offline Image Downloader", SetupNative.MB_YESNO | SetupNative.MB_ICONQUESTION); if (confirm != SetupNative.IDYES) return 0; } try { foreach (Process proc in Process.GetProcessesByName("M365IsoDownloader")) { try { proc.Kill(); proc.WaitForExit(2000); } catch { } } string startMenuLnk = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), AppDisplayName + ".lnk"); string desktopLnk = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), AppDisplayName + ".lnk"); if (File.Exists(startMenuLnk)) File.Delete(startMenuLnk); if (File.Exists(desktopLnk)) File.Delete(desktopLnk); Registry.CurrentUser.DeleteSubKeyTree(UninstallRegSubKey, throwOnMissingSubKey: false); string appExe = Path.Combine(installDir, "M365IsoDownloader.exe"); if (File.Exists(appExe)) File.Delete(appExe); // Schedule self-cleanup of Uninstall.exe and folder after process exits if (Directory.Exists(installDir)) { ProcessStartInfo psi = new ProcessStartInfo { FileName = "cmd.exe", Arguments = $"/C ping 127.0.0.1 -n 2 > nul & rmdir /S /Q \"{installDir}\"", CreateNoWindow = true, UseShellExecute = false }; Process.Start(psi); } if (!silent) { SetupNative.MessageBoxW(IntPtr.Zero, AppDisplayName + " has been uninstalled.", "Uninstall Complete", SetupNative.MB_OK | SetupNative.MB_ICONINFORMATION); } return 0; } catch (Exception ex) { if (!silent) { SetupNative.MessageBoxW(IntPtr.Zero, "Uninstall encountered an error:\n" + ex.Message, "Uninstall Error", SetupNative.MB_OK | SetupNative.MB_ICONERROR); } return 1; } } public int RunGui() { EnsureFont(); _cursorArrow = SetupNative.LoadCursorW(IntPtr.Zero, (IntPtr)SetupNative.IDC_ARROW); _cursorHand = SetupNative.LoadCursorW(IntPtr.Zero, (IntPtr)SetupNative.IDC_HAND); IntPtr hInstance = SetupNative.GetModuleHandleW(null); IntPtr hIcon = SetupNative.LoadIconW(hInstance, (IntPtr)32512); if (hIcon == IntPtr.Zero) hIcon = SetupNative.LoadIconW(IntPtr.Zero, (IntPtr)32512); fixed (char* cls = "M365IsoDownloaderSetupWnd") fixed (char* title = "Microsoft 365 Offline Image Downloader Setup") { SetupNative.WNDCLASSEXW wc = new SetupNative.WNDCLASSEXW { cbSize = (uint)sizeof(SetupNative.WNDCLASSEXW), style = SetupNative.CS_HREDRAW | SetupNative.CS_VREDRAW, lpfnWndProc = &StaticWndProc, hInstance = hInstance, hIcon = hIcon, hIconSm = hIcon, hCursor = _cursorArrow, lpszClassName = cls }; SetupNative.RegisterClassExW(ref wc); int sw = SetupNative.GetSystemMetrics(0); int sh = SetupNative.GetSystemMetrics(1); int winW = 580, winH = 445; _hwnd = SetupNative.CreateWindowExW( 0, cls, title, SetupNative.WS_OVERLAPPED | SetupNative.WS_CAPTION | SetupNative.WS_SYSMENU | SetupNative.WS_MINIMIZEBOX, Math.Max(40, (sw - winW) / 2), Math.Max(40, (sh - winH) / 2), winW, winH, IntPtr.Zero, IntPtr.Zero, hInstance, IntPtr.Zero); if (_hwnd == IntPtr.Zero) return 1; uint dpi = SetupNative.GetDpiForWindow(_hwnd); if (dpi > 0) _dpiScale = dpi / 96.0f; if (Math.Abs(_dpiScale - 1.0f) > 0.01f) { int scaledW = (int)Math.Round(winW * _dpiScale); int scaledH = (int)Math.Round(winH * _dpiScale); SetupNative.SetWindowPos(_hwnd, IntPtr.Zero, Math.Max(20, (sw - scaledW) / 2), Math.Max(20, (sh - scaledH) / 2), scaledW, scaledH, 0x0004); } int dark = 0; SetupNative.DwmSetWindowAttribute(_hwnd, 20, &dark, sizeof(int)); int round = 2; SetupNative.DwmSetWindowAttribute(_hwnd, 33, &round, sizeof(int)); uint captionCol = 0x00FFFFFF; SetupNative.DwmSetWindowAttribute(_hwnd, 35, &captionCol, sizeof(uint)); SetupNative.ShowWindow(_hwnd, SetupNative.SW_SHOW); SetupNative.UpdateWindow(_hwnd); while (SetupNative.GetMessageW(out SetupNative.MSG msg, IntPtr.Zero, 0, 0) > 0) { SetupNative.TranslateMessage(ref msg); SetupNative.DispatchMessageW(ref msg); } } return 0; } [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] private static nint StaticWndProc(IntPtr hwnd, uint msg, nuint wParam, nint lParam) { return Instance != null ? Instance.HandleMessage(hwnd, msg, wParam, lParam) : SetupNative.DefWindowProcW(hwnd, msg, wParam, lParam); } private nint HandleMessage(IntPtr hwnd, uint msg, nuint wParam, nint lParam) { switch (msg) { case SetupNative.WM_ERASEBKGND: return 1; case SetupNative.WM_DPICHANGED: { uint dpi = (uint)(wParam & 0xFFFF); if (dpi > 0) _dpiScale = dpi / 96.0f; SetupNative.RECT* rc = (SetupNative.RECT*)lParam; SetupNative.SetWindowPos(hwnd, IntPtr.Zero, rc->Left, rc->Top, rc->Right - rc->Left, rc->Bottom - rc->Top, 0x0014); SetupNative.InvalidateRect(hwnd, IntPtr.Zero, 0); return 0; } case SetupNative.WM_SETCURSOR: if (((int)lParam & 0xFFFF) == 1) { SetupNative.SetCursor(_hoveredId >= 0 ? _cursorHand : _cursorArrow); return 1; } break; case SetupNative.WM_MOUSEMOVE: { if (!_trackingMouse) { SetupNative.TRACKMOUSEEVENT tme = new SetupNative.TRACKMOUSEEVENT { cbSize = (uint)sizeof(SetupNative.TRACKMOUSEEVENT), dwFlags = 2, hwndTrack = hwnd }; SetupNative.TrackMouseEvent(ref tme); _trackingMouse = true; } float mx = (short)(lParam & 0xFFFF); float my = (short)((lParam >> 16) & 0xFFFF); int hit = HitTest(mx, my); if (hit != _hoveredId) { _hoveredId = hit; SetupNative.SetCursor(_hoveredId >= 0 ? _cursorHand : _cursorArrow); SetupNative.InvalidateRect(hwnd, IntPtr.Zero, 0); } return 0; } case SetupNative.WM_MOUSELEAVE: _trackingMouse = false; _mouseDown = false; _pressedId = -1; if (_hoveredId != -1) { _hoveredId = -1; SetupNative.InvalidateRect(hwnd, IntPtr.Zero, 0); } return 0; case SetupNative.WM_LBUTTONDOWN: { float mx = (short)(lParam & 0xFFFF); float my = (short)((lParam >> 16) & 0xFFFF); _mouseDown = true; _pressedId = HitTest(mx, my); SetupNative.InvalidateRect(hwnd, IntPtr.Zero, 0); return 0; } case SetupNative.WM_LBUTTONUP: { float mx = (short)(lParam & 0xFFFF); float my = (short)((lParam >> 16) & 0xFFFF); int hit = HitTest(mx, my); int wasPressed = _pressedId; _mouseDown = false; _pressedId = -1; SetupNative.InvalidateRect(hwnd, IntPtr.Zero, 0); if (hit >= 0 && hit == wasPressed) OnClick(hit); return 0; } case SetupNative.WM_PAINT: { IntPtr hdc = SetupNative.BeginPaint(hwnd, out SetupNative.PAINTSTRUCT ps); SetupNative.GetClientRect(hwnd, out SetupNative.RECT rc); int w = Math.Max(1, rc.Right - rc.Left); int h = Math.Max(1, rc.Bottom - rc.Top); IntPtr memDc = SetupNative.CreateCompatibleDC(hdc); SetupNative.BITMAPINFOHEADER bmi = new SetupNative.BITMAPINFOHEADER { biSize = (uint)sizeof(SetupNative.BITMAPINFOHEADER), biWidth = w, biHeight = -h, biPlanes = 1, biBitCount = 32 }; IntPtr hDib = SetupNative.CreateDIBSection(memDc, ref bmi, 0, out _, IntPtr.Zero, 0); IntPtr old = SetupNative.SelectObject(memDc, hDib); if (SetupNative.GdipCreateFromHDC(memDc, out IntPtr g) == 0 && g != IntPtr.Zero) { Paint(g, w, h, _dpiScale); SetupNative.GdipDeleteGraphics(g); } SetupNative.BitBlt(hdc, 0, 0, w, h, memDc, 0, 0, SetupNative.SRCCOPY); SetupNative.SelectObject(memDc, old); SetupNative.DeleteObject(hDib); SetupNative.DeleteDC(memDc); SetupNative.EndPaint(hwnd, ref ps); return 0; } case SetupNative.WM_CLOSE: SetupNative.DestroyWindow(hwnd); return 0; case SetupNative.WM_DESTROY: SetupNative.PostQuitMessage(0); return 0; } return SetupNative.DefWindowProcW(hwnd, msg, wParam, lParam); } private int HitTest(float x, float y) { if (!_installedSuccessfully) { if (_cbStartMenuRect.Contains(x, y)) return 1; if (_cbDesktopRect.Contains(x, y)) return 2; } if (_cbLaunchRect.Contains(x, y)) return 3; if (_primaryBtnRect.Contains(x, y)) return 4; if (_cancelBtnRect.Contains(x, y)) return 5; return -1; } private void OnClick(int id) { switch (id) { case 1: _createStartMenuShortcut = !_createStartMenuShortcut; SetupNative.InvalidateRect(_hwnd, IntPtr.Zero, 0); break; case 2: _createDesktopShortcut = !_createDesktopShortcut; SetupNative.InvalidateRect(_hwnd, IntPtr.Zero, 0); break; case 3: _launchAfterInstall = !_launchAfterInstall; SetupNative.InvalidateRect(_hwnd, IntPtr.Zero, 0); break; case 4: if (!_installedSuccessfully) { PerformInstallation(); } else { if (_launchAfterInstall) { string appExe = Path.Combine(_installDir, "M365IsoDownloader.exe"); if (File.Exists(appExe)) { SetupNative.ShellExecuteW(_hwnd, "open", appExe, null, _installDir, SetupNative.SW_SHOW); } } SetupNative.DestroyWindow(_hwnd); } break; case 5: SetupNative.DestroyWindow(_hwnd); break; } } private void PerformInstallation() { try { foreach (Process proc in Process.GetProcessesByName("M365IsoDownloader")) { try { proc.Kill(); proc.WaitForExit(2000); } catch { } } Directory.CreateDirectory(_installDir); string targetExe = Path.Combine(_installDir, "M365IsoDownloader.exe"); using (Stream? resStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("AppPayload.gz")) { if (resStream == null) throw new InvalidOperationException("Embedded application payload was not found."); using GZipStream gz = new GZipStream(resStream, CompressionMode.Decompress); using FileStream outFs = new FileStream(targetExe, FileMode.Create, FileAccess.Write, FileShare.None); gz.CopyTo(outFs); } // Copy installer binary as Uninstall.exe for Windows Settings -> Installed Apps support string? currentSetupExe = Environment.ProcessPath; string uninstallExe = Path.Combine(_installDir, "Uninstall.exe"); if (!string.IsNullOrEmpty(currentSetupExe) && File.Exists(currentSetupExe)) { File.Copy(currentSetupExe, uninstallExe, overwrite: true); } if (_createStartMenuShortcut) { string startMenuLnk = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), AppDisplayName + ".lnk"); SetupNative.CreateShortcut(startMenuLnk, targetExe, _installDir, "Check and download official Microsoft 365 en-US offline .img installers"); } if (_createDesktopShortcut) { string desktopLnk = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), AppDisplayName + ".lnk"); SetupNative.CreateShortcut(desktopLnk, targetExe, _installDir, "Check and download official Microsoft 365 en-US offline .img installers"); } using (RegistryKey? key = Registry.CurrentUser.CreateSubKey(UninstallRegSubKey)) { if (key != null) { long sizeKb = new FileInfo(targetExe).Length / 1024; key.SetValue("DisplayName", AppDisplayName); key.SetValue("DisplayVersion", AppVersion); key.SetValue("Publisher", "M365 Tools"); key.SetValue("DisplayIcon", targetExe); key.SetValue("InstallLocation", _installDir); key.SetValue("UninstallString", $"\"{uninstallExe}\" --uninstall"); key.SetValue("QuietUninstallString", $"\"{uninstallExe}\" --uninstall --silent"); key.SetValue("EstimatedSize", (int)sizeKb, RegistryValueKind.DWord); key.SetValue("NoModify", 1, RegistryValueKind.DWord); key.SetValue("NoRepair", 1, RegistryValueKind.DWord); } } _installedSuccessfully = true; _statusMessage = "Installation complete! Registered in Start Menu and Windows Installed Apps."; SetupNative.InvalidateRect(_hwnd, IntPtr.Zero, 0); } catch (Exception ex) { SetupNative.MessageBoxW(_hwnd, "Installation failed:\n" + ex.Message, "Setup Error", SetupNative.MB_OK | SetupNative.MB_ICONERROR); } } private void Paint(IntPtr g, int width, int height, float s) { SetupNative.GdipSetSmoothingMode(g, 4); SetupNative.GdipSetPixelOffsetMode(g, 4); SetupNative.GdipSetTextRenderingHint(g, 5); SetupNative.GdipGraphicsClear(g, 0xFFF3F5F8); IntPtr fTitle = CreateFont(17.5f * s, true); IntPtr fSub = CreateFont(12.2f * s, false); IntPtr fSemi = CreateFont(12.8f * s, true); IntPtr fBody = CreateFont(12.5f * s, false); IntPtr fSmall = CreateFont(11.6f * s, false); try { float padX = 24f * s; float headerH = 78f * s; float footerH = 62f * s; // Header FillRect(g, 0, 0, width, headerH, 0xFFFFFFFF); DrawLine(g, 0, headerH, width, headerH, 0xFFE2E8F0, 1f * s); float iconBox = 44f * s; float iconY = (headerH - iconBox) * 0.5f; FillRoundRect(g, new SetupNative.RectF(padX, iconY, iconBox, iconBox), 10f * s, _installedSuccessfully ? 0xFF0F7B0F : 0xFF0067C0); if (_installedSuccessfully) { DrawCheckmark(g, new SetupNative.RectF(padX + iconBox * 0.18f, iconY + iconBox * 0.18f, iconBox * 0.64f, iconBox * 0.64f), 2.8f * s); } else { DrawDownloadGlyph(g, padX + iconBox * 0.5f, iconY + iconBox * 0.5f, iconBox * 0.48f, 2.3f * s); } float titleX = padX + iconBox + 14f * s; float titleW = width - titleX - padX; DrawText(g, _installedSuccessfully ? "Installation Complete" : "Install Microsoft 365 Image Downloader", fTitle, new SetupNative.RectF(titleX, 16f * s, titleW, 24f * s), 0xFF0F172A, 0, true); DrawText(g, "Version 1.0.0 • .NET NativeAOT (win-x64) • en-US Offline Installer Utility", fSub, new SetupNative.RectF(titleX, 42f * s, titleW, 20f * s), 0xFF64748B, 0, true); // Main Card float cardY = headerH + 18f * s; float cardH = height - footerH - cardY - 18f * s; SetupNative.RectF card = new SetupNative.RectF(padX, cardY, width - 2 * padX, cardH); FillRoundRect(g, card, 10f * s, 0xFFFFFFFF); StrokeRoundRect(g, card, 10f * s, 0xFFE2E8F0, 1f * s); float cx = card.X + 18f * s; float cw = card.Width - 36f * s; float cy = card.Y + 16f * s; DrawText(g, "Destination Folder:", fSemi, new SetupNative.RectF(cx, cy, cw, 20f * s), 0xFF334155, 0, true); cy += 24f * s; SetupNative.RectF pathRect = new SetupNative.RectF(cx, cy, cw, 32f * s); FillRoundRect(g, pathRect, 6f * s, 0xFFF8FAFC); StrokeRoundRect(g, pathRect, 6f * s, 0xFFCBD5E1, 1f * s); DrawText(g, _installDir, fBody, new SetupNative.RectF(cx + 10f * s, cy, cw - 20f * s, 32f * s), 0xFF1E293B, 0, true, pathEllipsis: true); cy += 46f * s; if (!_installedSuccessfully) { _cbStartMenuRect = new SetupNative.RectF(cx, cy, cw, 24f * s); DrawOptionRow(g, _cbStartMenuRect, _createStartMenuShortcut, "Create Start Menu shortcut", fBody, _hoveredId == 1, s); cy += 32f * s; _cbDesktopRect = new SetupNative.RectF(cx, cy, cw, 24f * s); DrawOptionRow(g, _cbDesktopRect, _createDesktopShortcut, "Create Desktop shortcut", fBody, _hoveredId == 2, s); cy += 32f * s; } _cbLaunchRect = new SetupNative.RectF(cx, cy, cw, 24f * s); DrawOptionRow(g, _cbLaunchRect, _launchAfterInstall, "Launch Microsoft 365 Image Downloader when finished", fBody, _hoveredId == 3, s); DrawText(g, _statusMessage, fSmall, new SetupNative.RectF(cx, card.Y + card.Height - 28f * s, cw, 18f * s), _installedSuccessfully ? 0xFF0F7B0F : 0xFF64748B, 0, true); // Footer float footerY = height - footerH; FillRect(g, 0, footerY, width, footerH, 0xFFFFFFFF); DrawLine(g, 0, footerY, width, footerY, 0xFFE2E8F0, 1f * s); float btnH = 34f * s; float btnY = footerY + (footerH - btnH) * 0.5f; float primW = 128f * s; float cancelW = 92f * s; _primaryBtnRect = new SetupNative.RectF(width - padX - primW, btnY, primW, btnH); _cancelBtnRect = new SetupNative.RectF(_primaryBtnRect.X - 10f * s - cancelW, btnY, cancelW, btnH); if (!_installedSuccessfully) { DrawButton(g, _cancelBtnRect, "Cancel", fSemi, false, _hoveredId == 5, _mouseDown && _pressedId == 5, s); DrawButton(g, _primaryBtnRect, "Install Now", fSemi, true, _hoveredId == 4, _mouseDown && _pressedId == 4, s); } else { _cancelBtnRect = default; DrawButton(g, _primaryBtnRect, _launchAfterInstall ? "Finish & Launch" : "Finish", fSemi, true, _hoveredId == 4, _mouseDown && _pressedId == 4, s); } } finally { SetupNative.GdipDeleteFont(fTitle); SetupNative.GdipDeleteFont(fSub); SetupNative.GdipDeleteFont(fSemi); SetupNative.GdipDeleteFont(fBody); SetupNative.GdipDeleteFont(fSmall); } } private IntPtr CreateFont(float px, bool bold) { SetupNative.GdipCreateFont(_fontFamily, px, bold ? 1 : 0, 2, out IntPtr f); return f; } private static void DrawOptionRow(IntPtr g, SetupNative.RectF row, bool isChecked, string label, IntPtr font, bool hovered, float s) { float box = 19f * s; SetupNative.RectF cb = new SetupNative.RectF(row.X, row.Y + (row.Height - box) * 0.5f, box, box); if (isChecked) { FillRoundRect(g, cb, 5f * s, hovered ? 0xFF005A9E : 0xFF0067C0); DrawCheckmark(g, cb, 2.0f * s); } else { FillRoundRect(g, cb, 5f * s, hovered ? 0xFFF1F5F9 : 0xFFFFFFFF); StrokeRoundRect(g, cb, 5f * s, hovered ? 0xFF64748B : 0xFF94A3B8, 1.4f * s); } DrawText(g, label, font, new SetupNative.RectF(row.X + box + 10f * s, row.Y, row.Width - box - 10f * s, row.Height), 0xFF1E293B, 0, true); } private static void DrawCheckmark(IntPtr g, SetupNative.RectF r, float strokeW) { if (SetupNative.GdipCreatePen1(0xFFFFFFFF, strokeW, 2, out IntPtr pen) == 0) { SetupNative.GdipSetPenLineCap197819(pen, 2, 2, 2); SetupNative.GdipSetPenLineJoin(pen, 2); SetupNative.GdipDrawLine(g, pen, r.X + r.Width * 0.24f, r.Y + r.Height * 0.52f, r.X + r.Width * 0.43f, r.Y + r.Height * 0.72f); SetupNative.GdipDrawLine(g, pen, r.X + r.Width * 0.43f, r.Y + r.Height * 0.72f, r.X + r.Width * 0.77f, r.Y + r.Height * 0.30f); SetupNative.GdipDeletePen(pen); } } private static void DrawDownloadGlyph(IntPtr g, float cx, float cy, float size, float strokeW) { if (SetupNative.GdipCreatePen1(0xFFFFFFFF, strokeW, 2, out IntPtr pen) == 0) { SetupNative.GdipSetPenLineCap197819(pen, 2, 2, 2); SetupNative.GdipSetPenLineJoin(pen, 2); float half = size * 0.5f; SetupNative.GdipDrawLine(g, pen, cx, cy - half * 0.85f, cx, cy + half * 0.35f); SetupNative.GdipDrawLine(g, pen, cx - half * 0.58f, cy - half * 0.12f, cx, cy + half * 0.35f); SetupNative.GdipDrawLine(g, pen, cx + half * 0.58f, cy - half * 0.12f, cx, cy + half * 0.35f); SetupNative.GdipDrawLine(g, pen, cx - half * 0.72f, cy + half * 0.82f, cx + half * 0.72f, cy + half * 0.82f); SetupNative.GdipDeletePen(pen); } } private static void DrawButton(IntPtr g, SetupNative.RectF r, string text, IntPtr font, bool primary, bool hovered, bool pressed, float s) { uint bg = primary ? (pressed ? 0xFF004578u : (hovered ? 0xFF005A9Eu : 0xFF0067C0u)) : (pressed ? 0xFFE2E8F0u : (hovered ? 0xFFF8FAFCu : 0xFFFFFFFFu)); uint fg = primary ? 0xFFFFFFFFu : 0xFF1E293Bu; FillRoundRect(g, r, 6f * s, bg); if (!primary) StrokeRoundRect(g, r, 6f * s, hovered ? 0xFF94A3B8u : 0xFFCBD5E1u, 1f * s); DrawText(g, text, font, r, fg, 1, true); } private static void FillRect(IntPtr g, float x, float y, float w, float h, uint argb) { if (SetupNative.GdipCreateSolidFill(argb, out IntPtr b) == 0) { SetupNative.GdipFillRectangle(g, b, x, y, w, h); SetupNative.GdipDeleteBrush(b); } } private static void DrawLine(IntPtr g, float x1, float y1, float x2, float y2, uint argb, float w) { if (SetupNative.GdipCreatePen1(argb, w, 2, out IntPtr p) == 0) { SetupNative.GdipDrawLine(g, p, x1, y1, x2, y2); SetupNative.GdipDeletePen(p); } } private static IntPtr CreateRoundedPath(SetupNative.RectF r, float radius) { SetupNative.GdipCreatePath(0, out IntPtr path); float d = Math.Min(radius * 2f, Math.Min(r.Width, r.Height)); SetupNative.GdipAddPathArc(path, r.X, r.Y, d, d, 180f, 90f); SetupNative.GdipAddPathArc(path, r.X + r.Width - d, r.Y, d, d, 270f, 90f); SetupNative.GdipAddPathArc(path, r.X + r.Width - d, r.Y + r.Height - d, d, d, 0f, 90f); SetupNative.GdipAddPathArc(path, r.X, r.Y + r.Height - d, d, d, 90f, 90f); SetupNative.GdipClosePathFigure(path); return path; } private static void FillRoundRect(IntPtr g, SetupNative.RectF r, float radius, uint argb) { IntPtr path = CreateRoundedPath(r, radius); if (SetupNative.GdipCreateSolidFill(argb, out IntPtr b) == 0) { SetupNative.GdipFillPath(g, b, path); SetupNative.GdipDeleteBrush(b); } SetupNative.GdipDeletePath(path); } private static void StrokeRoundRect(IntPtr g, SetupNative.RectF r, float radius, uint argb, float strokeW) { IntPtr path = CreateRoundedPath(r, radius); if (SetupNative.GdipCreatePen1(argb, strokeW, 2, out IntPtr p) == 0) { SetupNative.GdipDrawPath(g, p, path); SetupNative.GdipDeletePen(p); } SetupNative.GdipDeletePath(path); } private static void DrawText(IntPtr g, string text, IntPtr font, SetupNative.RectF rect, uint argb, int align, bool vCenter, bool pathEllipsis = false) { SetupNative.GdipCreateStringFormat(0x00001000, 0, out IntPtr fmt); SetupNative.GdipSetStringFormatAlign(fmt, align); SetupNative.GdipSetStringFormatLineAlign(fmt, vCenter ? 1 : 0); SetupNative.GdipSetStringFormatTrimming(fmt, pathEllipsis ? 5 : 3); if (SetupNative.GdipCreateSolidFill(argb, out IntPtr b) == 0) { SetupNative.GdipDrawString(g, text, text.Length, font, ref rect, fmt, b); SetupNative.GdipDeleteBrush(b); } SetupNative.GdipDeleteStringFormat(fmt); } } public static class SetupProgram { public static int Main(string[] args) { SetupNative.CoInitializeEx(IntPtr.Zero, 2); SetupNative.GdiplusStartupInput input = new SetupNative.GdiplusStartupInput { GdiplusVersion = 1 }; SetupNative.GdiplusStartup(out nuint token, ref input, IntPtr.Zero); try { if (args.Length >= 1 && string.Equals(args[0], "--uninstall", StringComparison.OrdinalIgnoreCase)) { bool silent = args.Length >= 2 && string.Equals(args[1], "--silent", StringComparison.OrdinalIgnoreCase); return InstallerWindow.RunUninstall(silent); } InstallerWindow win = new InstallerWindow(); InstallerWindow.Instance = win; if (args.Length >= 2 && string.Equals(args[0], "--self-test-preview", StringComparison.OrdinalIgnoreCase)) { return win.RunPreviewPng(args[1]); } return win.RunGui(); } finally { InstallerWindow.Instance = null; if (token != 0) SetupNative.GdiplusShutdown(token); SetupNative.CoUninitialize(); } } } }