EdoardoTona.Rustino
0.5.6
See the version list below for details.
dotnet add package EdoardoTona.Rustino --version 0.5.6
NuGet\Install-Package EdoardoTona.Rustino -Version 0.5.6
<PackageReference Include="EdoardoTona.Rustino" Version="0.5.6" />
<PackageVersion Include="EdoardoTona.Rustino" Version="0.5.6" />
<PackageReference Include="EdoardoTona.Rustino" />
paket add EdoardoTona.Rustino --version 0.5.6
#r "nuget: EdoardoTona.Rustino, 0.5.6"
#:package EdoardoTona.Rustino@0.5.6
#addin nuget:?package=EdoardoTona.Rustino&version=0.5.6
#tool nuget:?package=EdoardoTona.Rustino&version=0.5.6
Rustino
Cross-platform native desktop windows with embedded web views, powered by Rust.
Inspired by Photino.NET.
Rustino replaces Photino's C++ native layer with Rust, using wry for the webview and tao for window management — the same libraries that power Tauri.
About this fork. This project started as a fork of Ivy-Interactive/Rustino and has since gone its own way: it is developed independently, is not kept in sync with the original repository, and its API and behavior differ from it (multiple windows, Blazor Hybrid, single instance and deep links, local files, and more). It is published under its own package names (see Installation); report issues and send pull requests here.
Architecture
Your .NET App
└── RustinoWindow (C#) ← Rustino.NET
└── P/Invoke
└── rustino_native ← Rustino.Native (Rust cdylib)
├── wry → WebView2 (Windows)
├── wry → WKWebView (macOS)
└── wry → WebKitGTK (Linux)
Installation
Rustino is published on NuGet as:
| Package | Contents |
|---|---|
EdoardoTona.Rustino |
RustinoWindow and the native libraries for Windows, macOS and Linux (x64, ARM64) |
EdoardoTona.Rustino.Reactive |
System.Reactive operators for the window events |
EdoardoTona.Rustino.Blazor |
Blazor Hybrid host, replacing Photino.Blazor |
dotnet add package EdoardoTona.Rustino
The namespaces stay Rustino.NET, Rustino.NET.Reactive and Rustino.Blazor.
Quick Start
using Rustino.NET;
var window = new RustinoWindow();
window
.SetTitle("My App")
.SetUseOsDefaultSize(false)
.SetSize(1280, 800)
.SetResizable(true)
.Center()
.Load(new Uri("https://example.com"));
window.WaitForClose();
Migrating from Photino
The API is identical. Replace the Photino.NET package with EdoardoTona.Rustino, then change two things:
- using Photino.NET;
+ using Rustino.NET;
- var window = new PhotinoWindow();
+ var window = new RustinoWindow();
All .Set*(), .Center(), .Load(), and .WaitForClose() calls remain the same. The types of ShowMessage follow the same rename: PhotinoDialogButtons, PhotinoDialogIcon and PhotinoDialogResult become RustinoDialogButtons, RustinoDialogIcon and RustinoDialogResult, with the same values.
For Blazor apps, replace Photino.Blazor with Rustino.Blazor:
- using Photino.Blazor;
+ using Rustino.Blazor;
- var builder = PhotinoBlazorAppBuilder.CreateDefault(args);
+ var builder = RustinoBlazorAppBuilder.CreateDefault(args);
API Reference
Configuration (pre-run)
| Method | Description |
|---|---|
SetTitle(string) |
Set the window title |
SetSize(int, int) |
Set window dimensions in pixels |
SetMinSize(int, int) |
Set minimum window size |
SetMaxSize(int, int) |
Set maximum window size |
SetPosition(int, int) |
Set window position |
SetUseOsDefaultSize(bool) |
Use OS default window size |
SetResizable(bool) |
Allow/prevent window resizing |
SetTopMost(bool) |
Keep window above all others |
SetChromeless(bool) |
Remove window decorations (title bar, borders) |
SetTransparent(bool) |
Enable transparent background |
SetMaximized(bool) |
Start maximized |
SetBackgroundColor(r, g, b, a) |
Set webview background color |
SetIconFile(string) |
Set window icon from .ico/.png file path. On macOS it is the Dock icon, unless the app bundle has its own (CFBundleIconFile / CFBundleIconName) |
SetIcon(Stream) |
Set window icon from a .NET stream (e.g. embedded resource) |
Center() |
Center window on the primary monitor |
SetDevToolsEnabled(bool) |
Enable the web inspector (right click › Inspect, F12 on Windows, OpenDevTools(); on macOS see Developer tools) |
SetContextMenuEnabled(bool) |
The browser's context menu on right click (on by default) |
SetBrowserControlsEnabled(bool) |
Windows: the browser's shortcuts, such as F5, Ctrl+R, Ctrl+F and Ctrl+P (on by default) |
SetScrollBarStyle(ScrollBarStyle) |
Windows: Default or FluentOverlay, the overlay scroll bars of Windows 11 |
SetAcceptFirstMouse(bool) |
macOS: the click that activates the window also reaches the page |
SetBackForwardGesturesEnabled(bool) |
Swipes go back and forward in the history (off by default) |
SetFileDropEnabled(bool) |
Files dropped on the window raise FileDrop with their paths (see Webview) |
SetJavascriptClipboardAccessEnabled(bool) |
Allow JS clipboard access |
SetIgnoreCertificateErrorsEnabled(bool) |
Ignore SSL certificate errors |
SetWebSecurityEnabled(bool) |
Enable/disable web security (CORS, etc.) |
SetMediaAutoplayEnabled(bool) |
Allow media to autoplay |
SetZoomHotkeysEnabled(bool) |
Enable Ctrl+/- zoom hotkeys |
SetUserAgent(string) |
Set custom user agent string |
SetUserDataFolder(string) |
Set webview data folder path |
AddInitScript(string) |
Add JavaScript to run before page loads |
RegisterCustomSchemeHandler(string, handler) |
Serve scheme:// requests from .NET (see Custom Schemes) |
Load(Uri) / Load(string) |
Navigate to a URL or local file (see Local files) |
LogVerbosity |
Set log verbosity (0 = silent) |
SetLogger(ILogger) |
Route native and callback logs to a Microsoft.Extensions.Logging logger |
SetApplicationId(string) |
Windows: the process AppUserModelID (taskbar grouping, pinning; pair it with RegisterNotificationAppId) |
Load() creates the native instance. Creation settings other than LogVerbosity can still be changed after
Load() and before the first WaitForClose(); Rustino applies them to the native configuration. Set LogVerbosity
before Load() because it is passed to the native constructor. Settings that affect window or webview creation
throw InvalidOperationException if changed after WaitForClose() starts. Runtime commands such as SetMenu(),
ExecuteScript() and SendWebMessage() can be sent before WaitForClose() and are delivered in order once the
window and webview exist.
Runtime (post-run)
| Method | Description |
|---|---|
Minimize() |
Minimize the window |
Maximize() |
Maximize the window |
Restore() |
Restore from minimized/maximized |
SetFullscreen(bool) |
Enter/exit fullscreen |
SetVisible(bool) |
Show/hide the window |
Focus() |
Bring focus to the window |
Activate(string? activationToken = null) |
Show and restore the window, then request focus. On Linux, pass the launcher activation token when available. |
Close() |
Close the window |
RustinoWindow.OpenExternal(string) |
Open an http, https or mailto URL in the system's default application |
ExecuteScript(string) |
Evaluate JavaScript in the webview |
SendWebMessage(string) |
Post a message to the webview |
SetZoom(double) |
Set webview zoom factor |
Print() |
Open the system print dialog for the page |
Reload() |
Reload the page (a page loaded from an HTML string is loaded again) |
OpenDevTools() / CloseDevTools() |
Open or close the web inspector (needs SetDevToolsEnabled(true); closing isn't supported on Windows; on macOS see Developer tools) |
ClearBrowsingData() |
Delete the cookies, the cache and the storage of every site |
GetCookies(string?) / SetCookie(RustinoCookie) / DeleteCookie(RustinoCookie) |
Read and change the webview's cookies (see Webview) |
SetBadgeCount(int?, string?, string?) |
Set taskbar/dock badge with optional bg/fg hex colors |
ClearBadge() |
Remove the taskbar/dock badge |
WaitForClose() |
Block until the window is closed; throws RustinoException if native window or webview creation fails (see Multiple Windows) |
Dispose() |
Release native resources (RustinoWindow implements IDisposable) |
Multiple Windows
The first window runs the app's event loop on the thread that calls its WaitForClose(), which must be the main
thread on macOS. Windows started while it runs join that event loop. This works the same way on every platform,
macOS included, where AppKit allows only one event loop. Call their WaitForClose() from another thread: it only
waits for the window to close.
var second = new RustinoWindow().SetTitle("Second window").Load("wwwroot/second.html");
second.WebMessageReceived += (_, message) => Console.WriteLine(message);
new Thread(() =>
{
second.WaitForClose();
second.Dispose();
}) { IsBackground = true }.Start();
- The events of every window are raised on the first window's thread.
- Windows started at the same moment don't create two event loops: the first one starts it, and the others wait for it and join.
- A window closes on its own (user or
Close()). Closing the first window closes them all, and everyWaitForClose()returns. - Calling
WaitForClose()of another window on the event loop thread (e.g. from an event handler) throwsRustinoException, because that thread can't block. Start a thread as above. - On macOS the menu bar belongs to the app: set it from the first window.
SetMenufrom another window replaces it.
Child and modal windows
SetParent(window) makes a window a child of a running window: it stays above its parent and closes with it.
SetModal(true) also blocks the parent until the child closes. Both are pre-run settings.
var settings = new RustinoWindow().SetTitle("Settings").SetSize(480, 360)
.SetParent(mainWindow).SetModal(true)
.Load("wwwroot/settings.html");
new Thread(() => { settings.WaitForClose(); settings.Dispose(); }) { IsBackground = true }.Start();
| Platform | Child | Modal |
|---|---|---|
| Windows | Owned window: above its owner, minimized with it, no taskbar button of its own | The parent is disabled |
| macOS | Child window: moves with the parent | A sheet attached to the parent's title bar |
| Linux | Transient window | A modal GTK window, which blocks every other window of the app |
The parent must be running when the child starts, otherwise the child opens as a top-level window (with a warning in the log).
Single Instance
Acquire the app id at the start of Main. The first process becomes primary; later processes forward their
arguments and return with Status == Forwarded after the primary queues the launch:
using var single = RustinoSingleInstance.Acquire("com.company.product", new SingleInstanceOptions
{
Arguments = args,
});
if (single.Status == SingleInstanceStatus.Forwarded) return;
if (single.Status == SingleInstanceStatus.ForwardFailed)
{
Console.Error.WriteLine("The running instance did not respond.");
return;
}
var window = new RustinoWindow().Load("wwwroot/index.html");
single.SecondInstanceStarted += (_, e) => OpenFiles(e.Args, e.WorkingDirectory);
single.MainWindow = window; // restores and activates after each forwarded launch
window.WaitForClose();
SingleInstanceOptions |
Default | Description |
|---|---|---|
Arguments |
the arguments of Main |
Sent to the primary by a later process |
ForwardAutomatically |
true |
false returns Status == Secondary without forwarding: call ForwardToPrimary(args?, timeout?) yourself |
Timeout |
5 s | How long to wait for a primary that is still starting (at most 5 minutes) |
ActivateMainWindow |
true |
Activate MainWindow after each forwarded launch |
Logger |
null |
Receives listener and handler failures |
SecondInstanceEventArgs carries Args, WorkingDirectory, ProcessId and ActivationToken (Linux) of the
later process. Exceptions thrown by the handlers are logged and raise UnhandledException. Disposing the instance
stops listening, lets the handlers finish the launches already acknowledged, then releases the app id.
SecondInstanceStarted runs sequentially on a background thread, so UI frameworks must dispatch UI work to their
own thread. Messages received before a handler is attached are held in a bounded queue. Set ActivateMainWindow
to false in a handler when that launch should not activate the configured window. Linux launchers may provide
XDG_ACTIVATION_TOKEN or DESKTOP_STARTUP_ID; Rustino forwards it to Activate() when it activates the window.
On macOS, Finder and LaunchServices may reactivate a bundled app without starting another process; this API also
covers direct executable launches.
Deep Links
After registering a custom scheme with the operating system or declaring it in the macOS app bundle, use
AttachDeepLinks() to route URLs from the initial command line and later single-instance launches through
UrlsOpened on the window thread:
window.UrlsOpened += (_, urls) =>
{
foreach (var url in urls) HandleAfterValidation(url);
};
window.AttachDeepLinks(single, "notes");
RustinoDeepLinks.GetCurrent("notes") returns matching absolute URLs from the current process arguments.
The helper filters only by the supplied scheme allow-list; it does not register the scheme or validate URL
hosts, paths, OAuth state, or tokens. Treat every URL as untrusted input.
Start at login
RustinoAutoStart starts the app when the user logs in, for the current user only (no service, no admin rights): a
value of the Run registry key on Windows, a launch agent in ~/Library/LaunchAgents on macOS, an entry in
~/.config/autostart on Linux. The user can also turn it off from the system, and the app sees it, so its settings
always show the real state:
using var autoStart = new RustinoAutoStart("com.company.product");
// The settings page: a switch bound to the real state
settings.StartAtLogin = autoStart.Status == AutoStartStatus.Enabled;
settings.ShowSystemSettingsHint = autoStart.Status == AutoStartStatus.DisabledBySystem;
autoStart.StatusChanged += (_, status) => window.SendWebMessage($"autostart:{status}"); // thread pool thread
// The user flips the switch
var status = on ? autoStart.Enable() : autoStart.Disable();
if (status == AutoStartStatus.DisabledBySystem) // macOS: Login Items keeps its choice
RustinoAutoStart.OpenSystemSettings();
AutoStartStatus |
Meaning |
|---|---|
Disabled |
No entry: the app doesn't start at login |
Enabled |
The app starts at login |
DisabledBySystem |
The entry is there, but the user turned it off from the system |
Unsupported |
No start at login here (a Flatpak sandbox) |
Status reads the system on each call. StatusChanged (and WhenStatusChanged) reports the changes of Enable,
Disable and the system: once someone listens, the system is checked every AutoStartOptions.PollInterval (2 s). An
exception thrown by a handler or observer doesn't stop the others nor the checks, and doesn't reach Enable or
Disable: it raises UnhandledException.
The launch at login gets --autostart (RustinoAutoStart.LaunchArgument) after the arguments of
AutoStartOptions.Arguments, so the app can decide what to show: for instance only the tray icon, and the window
when the user asks for it:
var startHidden = RustinoAutoStart.WasLaunchedAtLogin && settings.StartInTray; // the app's own choice
var window = new RustinoWindow()
.SetVisible(!startHidden) // before WaitForClose: the window is created hidden
.SetTrayIcon("icon.png", tooltip: "My App", menu: trayMenu)
.Load("wwwroot/index.html");
window.TrayIconClicked += (_, _) => window.SetVisible(true).Focus();
window.WaitForClose();
AutoStartOptions |
Default | Description |
|---|---|---|
Arguments |
none | Arguments of the launch at login, before --autostart |
ExecutablePath |
the running executable | With dotnet app.dll, the dotnet host and the app's assembly |
DisplayName |
the app id | Linux: the name in the startup applications |
PollInterval |
2 s | How often StatusChanged checks the system |
When the user turns the entry off from the system:
- Windows: Task Manager (Startup apps) and Settings › Apps › Startup leave the
Runvalue and mark it off inExplorer\StartupApproved\Run:StatusisDisabledBySystem.Enable()turns it on again and clears that mark, since the user asked for it from the app. MSIX packaged apps can't use theRunkey: they declare aStartupTaskin their manifest.OpenSystemSettings()opens Settings › Apps › Startup. - macOS: System Settings › General › Login Items › Allow in the Background turns the agent off:
StatusisDisabledBySystem(macOS 13 and later, throughSMAppService.statusForLegacyURL; earlier versions have no such switch). An app can't turn it on again by itself:Enable()keeps returningDisabledBySystemuntil the user turns the switch back on, so show a hint and a button that callsOpenSystemSettings(), which opens Login Items. The agent shows there with the app's name and icon when the app runs from a bundle (AssociatedBundleIdentifiers), and macOS notifies the user when it's added. - Linux: GNOME's Startup Applications sets
X-GNOME-Autostart-enabled=falseand KDE setsHidden=true:StatusisDisabledBySystem, andEnable()turns it on again. Tools that delete the entry make itDisabled.OpenSystemSettings()returnsfalse: desktops have no common page.
The entry points to the executable that called Enable(). If an update moves the app (e.g. versioned folders),
refresh it at startup without overriding the user's choice: if (autoStart.Status == AutoStartStatus.Enabled) autoStart.Enable();. Disable() removes the entry; disposing the object only stops the checks.
Safe storage
RustinoSafeStorage encrypts the app's secrets (tokens, passwords) so that only the current user can decrypt them,
and the app keeps the bytes in its own files:
var storage = new RustinoSafeStorage("com.company.product");
var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApp", "token.bin");
if (storage.IsEncryptionAvailable)
File.WriteAllBytes(file, storage.EncryptString(token));
var token = storage.DecryptString(File.ReadAllBytes(file)); // CryptographicException: not ours, or altered
storage.ResetKey(); // sign out: the old bytes no longer decrypt (macOS, Linux)
| Platform | How |
|---|---|
| Windows | DPAPI of the user (CryptProtectData), with the app id as entropy |
| macOS | AES-256-GCM with a random key of the app, in the login Keychain as "<app id> Safe Storage" |
| Linux | AES-256-GCM with a random key of the app, in the Secret Service through libsecret (GNOME Keyring, KWallet) |
Encrypt/Decrypt take bytes, EncryptString/DecryptString UTF-8 text. The bytes decrypt only for the same user
and app id on the same platform (on Windows, on the same machine too). On macOS and Linux the key is created the first
time; Encrypt and IsEncryptionAvailable read it from the store each time, so a ResetKey in another process of
the app takes effect, while Decrypt keeps it in memory. The system may ask the user to allow access or to unlock the
keychain, and the call waits for the answer (call it off the UI thread). The processes of the app take turns through a
lock file ($XDG_RUNTIME_DIR on Linux, $TMPDIR on macOS), so two of them never create two keys. IsEncryptionAvailable is false when there's no key store (Linux
without a Secret Service, e.g. no keyring daemon or no D-Bus session) or the user refused access; then Encrypt throws
RustinoException. Rustino never falls back to a weaker key: decide whether to keep the secret in memory only or ask
for it again. libsecret (0.19 or later: Ubuntu 20.04, Debian 11) is loaded when first needed, so the library still
loads without it.
Splashscreen
A borderless window showing an image while the app starts; it closes on Close() or Dispose(). Windows only:
macOS and Linux create windows on the main thread, which the app's window takes once it runs, so there the
constructors throw PlatformNotSupportedException. Check RustinoSplashscreen.IsSupported:
using (var splash = RustinoSplashscreen.IsSupported ? new RustinoSplashscreen("splash.png", width: 400, height: 400) : null)
{
LoadSettings(); // slow startup work
}
// From an embedded resource
using var splash = RustinoSplashscreen.FromImage(stream, 400, 300);
Local files
Load takes a path or a file: URL. A relative path is resolved against the current directory, then against the app's directory. The page is served from rustino-file://localhost/<full path> rather than file://: webviews don't deliver window.ipc messages from file: pages, and the scheme gives the page an origin. The files in the folder of the loaded file and its subfolders can be referenced with relative URLs (css/app.css); nothing outside the folders of loaded files is served. PageLoaded and Navigating report the page's URL: rustino-file://localhost/..., or http://rustino-file.localhost/... on Windows, where WebView2 serves custom schemes from http://<scheme>.localhost/. rustino-file can't be registered with RegisterCustomSchemeHandler.
window.Load("wwwroot/index.html"); // rustino-file://localhost/<app folder>/wwwroot/index.html
Custom Schemes
Serve content for a custom URL scheme directly from .NET (same signature as Photino). Register handlers before WaitForClose(); returning null produces a 404:
window.RegisterCustomSchemeHandler("app", (sender, scheme, url, out contentType) =>
{
contentType = "text/html";
return new MemoryStream("<h1>Hello from .NET</h1>"u8.ToArray());
});
window.Load("app://localhost/");
On Windows, WebView2 sees custom schemes as http://<scheme>.localhost/; handlers still receive the original <scheme>://... URLs.
Dialogs
Native cross-platform file dialogs (powered by rfd):
// Open file (single)
string[]? files = window.ShowOpenFileDialog(
title: "Select an image",
filters: [new FileFilter("Images", "jpg", "png", "gif")]);
// Open files (multi-select)
string[]? files = window.ShowOpenFileDialog(
title: "Select files",
multiSelect: true);
// Save file
string? path = window.ShowSaveFileDialog(
title: "Save as",
defaultPath: "document.pdf",
filters: [new FileFilter("PDF", "pdf")]);
// Select folder
string[]? folders = window.ShowSelectFolderDialog(
title: "Choose output directory");
All dialogs return null when canceled. File filters use the format new FileFilter("Name", "ext1", "ext2", ...).
Message boxes use the same signature as Photino's ShowMessage:
var answer = window.ShowMessage("Unsaved changes", "Save the document before closing?",
RustinoDialogButtons.YesNoCancel, RustinoDialogIcon.Question);
if (answer == RustinoDialogResult.Yes) Save();
Buttons: Ok, OkCancel, YesNo, YesNoCancel, RetryCancel, AbortRetryIgnore. Icons: Info, Warning, Error, Question (shown as Info on macOS). Closing the box without a button returns Cancel, or Ok when Ok is the only button.
While the window runs, every dialog is modal for it: a sheet on macOS, owned by the window on Windows (which can't be clicked until the dialog closes), transient for it on Linux. They can be called from any thread, including the event handlers; before the window runs they have no parent. Message boxes use MessageBoxW on Windows (localized buttons), NSAlert on macOS and GtkMessageDialog on Linux; before the window runs, macOS shows a system alert instead of an NSAlert. On Linux file dialogs go through the XDG desktop portal.
Notifications
Native cross-platform toast notifications (powered by notify-rust):
// Static — no window instance required
RustinoWindow.ShowNotification("Download Complete", "Your file has been saved.");
// With icon (file path)
RustinoWindow.ShowNotification("Alert", "Something happened", iconPath: "/path/to/icon.png");
// With icon (embedded resource stream)
using var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("MyApp.notify.png")!;
RustinoWindow.ShowNotification("Alert", "Something happened", stream);
Uses WinRT Toast (Windows), NSUserNotification (macOS), and D-Bus (Linux).
Windows: register your appId
On Windows, a toast is shown under the AppUserModelID passed as appId. Windows only displays toasts for an id it knows (a packaged app, a Start Menu shortcut carrying the id, or a registry registration) and silently drops the others, while ShowNotification still returns true. Without appId, notifications fall back to the Windows PowerShell id and show its name and icon.
Unpackaged apps (a plain .exe, a dotnet tool) should register their id once at startup:
RustinoWindow.RegisterNotificationAppId("MyCompany.MyApp", "My App", iconPath: @"C:\path\to\icon.png");
RustinoWindow.ShowNotification("Hello", "Shown as My App", appId: "MyCompany.MyApp");
This writes HKCU\Software\Classes\AppUserModelId\<appId> (display name and icon; no admin rights, no shortcut). The icon must be an image file (.png/.ico) that stays at that path; registering again without iconPath removes the previous icon. appId must be a valid AppUserModelID such as CompanyName.ProductName (at most 128 characters, no spaces or backslashes); otherwise the call returns false on every platform. On macOS and Linux a valid id is accepted without writing anything.
Menus
Native cross-platform application menus and context menus (powered by muda):
// Application menu bar
var menu = new RustinoMenu()
.AddSubmenu("File", file => file
.AddItem("new", "New", accelerator: "CmdOrCtrl+N", iconPath: "new.png")
.AddItem("open", "Open...", accelerator: "CmdOrCtrl+O")
.AddSeparator()
.AddItem("exit", "Exit"))
.AddSubmenu("Edit", edit => edit
.AddPredefinedItem(PredefinedMenuItem.Undo)
.AddPredefinedItem(PredefinedMenuItem.Redo)
.AddSeparator()
.AddPredefinedItem(PredefinedMenuItem.Copy)
.AddPredefinedItem(PredefinedMenuItem.Paste, label: "Paste here")
.AddSeparator()
.AddCheckItem("wordwrap", "Word Wrap", isChecked: true, accelerator: "Alt+Z"))
.AddWindowMenu("Window", win => win
.AddPredefinedItem(PredefinedMenuItem.Minimize)
.AddPredefinedItem(PredefinedMenuItem.Maximize))
.AddHelpMenu("Help", help => help
.AddItem("about", "About"));
window.SetMenu(menu);
// Context menu (right-click)
var ctx = new RustinoMenu()
.AddItem("cut", "Cut")
.AddItem("copy", "Copy")
.AddItem("paste", "Paste");
window.ShowContextMenu(ctx);
// Handle clicks
window.MenuItemClicked += (_, id) => Console.WriteLine($"Clicked: {id}");
// A click toggles a check item: its new state comes after MenuItemClicked
window.MenuItemCheckedChanged += (_, e) => Console.WriteLine($"{e.Id}: {e.IsChecked}");
// Change items without rebuilding the menu
window.SetMenuItemEnabled("open", false);
window.SetMenuItemChecked("wordwrap", false);
window.SetMenuItemText("open", "Open Recent...");
// Remove menu bar
window.RemoveMenu();
The SetMenuItem* methods change every item with that id in the menu bar and in the tray menu, until the menu is set again. Items with the same id stay in sync when the user toggles one of them. A context menu is built from its RustinoMenu at every ShowContextMenu, so it always shows the values of the definition: build it when you show it, with the current values (for a check item, the state received from MenuItemCheckedChanged).
iconPath shows an image next to the label, scaled to the menu's icon size; if it can't be read, the item has no icon.
On macOS, the system lists the open windows in the menu added with AddWindowMenu and adds a search field to the one added with AddHelpMenu; on Windows and Linux both are normal submenus. Until SetMenu, macOS shows a standard menu bar: the application menu, Edit and Window.
Predefined items run a native OS action and don't raise MenuItemClicked. On macOS, a custom menu bar replaces the default one: include the predefined Edit items, otherwise Cmd+C/V/X/A stop working in the webview.
On macOS, SetMenu also prepends the standard application menu (About, Hide, Hide Others, Show All, Quit), shown with the app name, so your first submenu (e.g. File) stays visible. Replace it with AddAppMenu (ignored on Windows and Linux):
var menu = new RustinoMenu()
.AddAppMenu(app => app
.AddPredefinedItem(PredefinedMenuItem.About)
.AddSeparator()
.AddItem("settings", "Settings…", accelerator: "CmdOrCtrl+,")
.AddSeparator()
.AddPredefinedItem(PredefinedMenuItem.Quit))
.AddSubmenu("File", file => file.AddItem("open", "Open..."));
The predefined About item opens the native About panel with the window icon and the values of SetAboutName, SetAboutVersion, SetAboutCopyright, SetAboutComments, AddAboutAuthor, SetAboutWebsite and SetAboutLicense (the macOS panel shows the last four as credits). Without SetAboutName, macOS uses the app name shown in the menu bar. The values are read when a menu is set: after changing them (or the icon) at runtime, call SetMenu again. For a fully custom About, use a normal item and handle MenuItemClicked.
The default macOS menus (application, Edit, Window) and the predefined items without a label are in English. To translate them, set your own menu bar with the labels in the app's language:
var menu = new RustinoMenu()
.AddAppMenu(app => app
.AddPredefinedItem(PredefinedMenuItem.About, "Informazioni su MyApp")
.AddSeparator()
.AddPredefinedItem(PredefinedMenuItem.Hide, "Nascondi MyApp")
.AddPredefinedItem(PredefinedMenuItem.HideOthers, "Nascondi altre")
.AddPredefinedItem(PredefinedMenuItem.ShowAll, "Mostra tutte")
.AddSeparator()
.AddPredefinedItem(PredefinedMenuItem.Quit, "Esci da MyApp"))
.AddSubmenu("Modifica", edit => edit
.AddPredefinedItem(PredefinedMenuItem.Undo, "Annulla")
.AddPredefinedItem(PredefinedMenuItem.Redo, "Ripeti")
.AddSeparator()
.AddPredefinedItem(PredefinedMenuItem.Cut, "Taglia")
.AddPredefinedItem(PredefinedMenuItem.Copy, "Copia")
.AddPredefinedItem(PredefinedMenuItem.Paste, "Incolla")
.AddPredefinedItem(PredefinedMenuItem.SelectAll, "Seleziona tutto"))
.AddWindowMenu("Finestra", window => window
.AddPredefinedItem(PredefinedMenuItem.Minimize, "Contrai")
.AddPredefinedItem(PredefinedMenuItem.Maximize, "Zoom")
.AddSeparator()
.AddPredefinedItem(PredefinedMenuItem.BringAllToFront, "Porta tutto in primo piano"));
Support depends on the platform (muda):
| Predefined item | macOS | Windows | Linux |
|---|---|---|---|
About |
OK | OK, no icon | OK |
Cut, Copy, Paste, SelectAll, Undo, Redo |
OK | OK | OK |
Minimize, Maximize, Hide, CloseWindow, Quit |
OK | OK | omitted |
Fullscreen, HideOthers, ShowAll, Services, BringAllToFront |
OK | shown disabled | omitted |
"Omitted" items are not added to the menu. On Linux the edit items act on the focused webview.
On Windows, Ctrl+C/X/V/A/Z/Y go to the webview, which handles them natively, unless a custom item uses them: the item then replaces the native shortcut. If the menu also has the predefined item with the same shortcut (Copy, Cut, Paste, Select All, Undo, Redo), the shortcut stays with the webview.
System Tray
Native cross-platform system tray icon with optional context menu (powered by tray-icon):
// Tray icon with tooltip and context menu
var trayMenu = new RustinoMenu()
.AddItem("show", "Show Window")
.AddItem("hide", "Hide Window")
.AddSeparator()
.AddItem("quit", "Quit");
window.SetTrayIcon("icon.png", tooltip: "My App", menu: trayMenu);
// From embedded resource (Stream)
using var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("MyApp.tray.png")!;
window.SetTrayIcon(stream, tooltip: "My App", menu: trayMenu);
// macOS: a monochrome template icon that follows the light or dark menu bar, text next to
// the icon, and the menu only on right click
window.SetTrayIcon("tray-template.png", tooltip: "My App", menu: trayMenu,
title: "3", isTemplateIcon: true, menuOnLeftClick: false);
window.SetTrayTitle("4");
// Handle tray icon clicks
window.TrayIconClicked += (_, e) =>
{
if (e.Button == TrayMouseButton.Left)
window.SetVisible(true);
};
// Remove tray icon
window.RemoveTrayIcon();
TrayIconClicked is raised once per click, with the button and the cursor position in physical pixels. It's raised when the button is released, or when it's pressed if the click opens the tray menu (on macOS the menu takes the release). By default both left and right click open the menu: with menuOnLeftClick: false left clicks only raise TrayIconClicked.
A template icon uses only the image's alpha channel, so a colored icon turns into a solid silhouette: use it with a black shape on a transparent background.
On Windows pass an .ico with the small sizes (16, 20, 24, 32): it's loaded at the system's small icon size from its closest frame. Any other image is used at its own size and the shell shrinks it without filtering, which leaves jagged edges.
| macOS | Windows | Linux | |
|---|---|---|---|
TrayIconClicked |
OK | OK | never raised¹ |
tooltip |
OK | OK | not supported² |
title, SetTrayTitle |
OK | not supported | only on some desktops |
isTemplateIcon |
OK | ignored | ignored |
menuOnLeftClick |
OK | OK | ignored: any click opens the menu |
¹ On Linux the tray icon is an AppIndicator (libayatana-appindicator), which doesn't report clicks: put every action in the tray menu.
² The tooltip is the icon's accessible name; without one, the window title is used (macOS, Windows). On Linux tray-icon doesn't expose the AppIndicator title, so the icon has no accessible name: set title if the icon must be identified by assistive technologies.
Taskbar Badge
Set a numeric badge on the taskbar icon (Windows) or dock icon (macOS, Linux):
// Set badge with default colors (red background, white text)
window.SetBadgeCount(5);
// Set badge with custom colors (Windows only, hex format)
window.SetBadgeCount(5, background: "#4A154B", foreground: "#FFFFFF");
// Clear the badge
window.ClearBadge();
On Windows, this renders an overlay icon on the taskbar button using a 32px anti-aliased circle with bold Segoe UI text. Numbers above 99 display as "99+". The background and foreground parameters accept #RRGGBB hex strings and default to #E01E5A (red) and #FFFFFF (white).
On macOS, the native dockTile.setBadgeLabel API is used — color parameters are ignored as the OS controls badge appearance.
On Linux, the count goes to the dock through the Unity LauncherEntry D-Bus API (Ubuntu Dock, Dash to Dock, KDE Plasma). The dock finds the app by its .desktop file: <executable name>.desktop unless you call SetDesktopFileName("com.example.App.desktop").
Monitors
Enumerate connected displays with position, resolution, and DPI scale factor:
// Get all monitors
MonitorInfo[] monitors = window.GetMonitors();
foreach (var m in monitors)
Console.WriteLine($"{m.Name}: {m.Width}x{m.Height} at ({m.X},{m.Y}), scale={m.ScaleFactor}, primary={m.IsPrimary}");
// Get the monitor containing this window
MonitorInfo? current = window.GetCurrentMonitor();
// DPI-aware positioning: center window on a specific monitor
var target = monitors.First(m => !m.IsPrimary);
var (w, h) = window.GetSize();
window.SetPosition(
target.X + (target.Width - w) / 2,
target.Y + (target.Height - h) / 2);
MonitorInfo properties: Name, X, Y, Width, Height, ScaleFactor, IsPrimary.
MonitorsChanged reports monitors added, removed, or with new bounds, scale factor or primary status
(MonitorsChangedEventArgs: .Monitors, .Added, .Removed, .Changed, matched by name, and by bounds between monitors of the same model). The platforms
don't tell the webview layer about these changes, so while a handler or an observer of WhenMonitorsChanged is
attached the window compares the monitors every second.
window.MonitorsChanged += (_, e) =>
{
foreach (var m in e.Removed) Console.WriteLine($"Disconnected: {m.Name}");
if (window.GetCurrentMonitor() is null) window.Center();
};
// Cursor position on the screen, in physical pixels (null before the window runs; 0, 0 on Wayland)
if (window.GetCursorPosition() is var (x, y)) Console.WriteLine($"{x}, {y}");
Global Shortcuts
A global shortcut reaches the app even while another app has the focus. It belongs to the window that registers
it, raises that window's GlobalShortcutPressed (with the accelerator as it was registered), and is released when
the window closes. Accelerators use the syntax of the menu accelerators (CmdOrCtrl+Shift+K, Alt+F4, Super+Space).
window.GlobalShortcutPressed += (_, accelerator) => window.Activate();
if (!window.RegisterGlobalShortcut("CmdOrCtrl+Shift+Space"))
Console.WriteLine("Invalid, or another app has it");
| Method | Description |
|---|---|
RegisterGlobalShortcut(string) |
false when the accelerator is invalid or another window or app has it. Before the window runs it's registered when the window starts, and only an invalid accelerator returns false |
UnregisterGlobalShortcut(string) |
false when the window hadn't registered it |
UnregisterAllGlobalShortcuts() |
Releases every shortcut of the window |
IsGlobalShortcutRegistered(string) |
Whether the running window registered it |
On Linux global shortcuts need X11: without an X11 display RegisterGlobalShortcut returns false, and in a Wayland session (through XWayland) they don't reach the app while a Wayland window has the focus.
Native Window Features
window
.SetTheme(WindowTheme.Dark) // title bar, native controls, prefers-color-scheme
.SetMacTitleBarStyle(MacTitleBarStyle.Overlay) // macOS: the page extends under the traffic lights
.SetMacTrafficLightPosition(14, 12);
window.ThemeChanged += (_, theme) => Console.WriteLine($"Now {theme}");
// Later, while the window runs
window.SetProgressBar(ProgressBarState.Normal, 40); // taskbar button / Dock icon
window.RequestUserAttention(UserAttentionType.Critical);
The platform limits below hold both before the window runs and while it runs.
| Method / property | Description |
|---|---|
SetTheme(WindowTheme) |
System, Light or Dark. Windows applies it to the window (dark title bar) and to WebView2; macOS and Linux to the whole app |
Theme |
Current theme, Light or Dark |
ScaleFactor |
Physical pixels per logical pixel on the window's monitor |
SetProgressBar(ProgressBarState, int?) / ClearProgressBar() |
Progress on the taskbar button (Windows), the Dock icon (macOS) or the dock icon (Linux, LauncherEntry: see Taskbar Badge) |
RequestUserAttention(UserAttentionType) / CancelUserAttentionRequest() |
Flashes the taskbar button, bounces the Dock icon or sets the urgency hint, until the app is focused |
Beep() |
Plays the system alert sound (MessageBeep, NSBeep, the GDK display bell) |
SetShadow(bool) |
Window shadow (Windows: chromeless windows; macOS: all windows) |
SetSkipTaskbar(bool) |
No taskbar button, for apps that live in the tray. On macOS the app leaves the Dock and the app switcher |
SetContentProtection(bool) |
Keeps the window out of screenshots and recordings (Windows, macOS) |
SetVisibleOnAllWorkspaces(bool) |
Shows the window on every virtual desktop (macOS, Linux) |
SetClosable(bool) / SetMinimizable(bool) / SetMaximizable(bool) |
Enable the title bar buttons. Linux: only SetClosable, as a request the window manager may ignore; minimize and maximize can't be disabled |
SetAlwaysOnBottom(bool) |
Keeps the window below the others, replacing SetTopMost. Linux: a request to the window manager, not supported on Wayland |
SetIgnoreCursorEvents(bool) |
Mouse clicks go through the window, for overlays |
SetMacTitleBarStyle(MacTitleBarStyle) |
macOS: Default, Transparent or Overlay (no title, the page under the traffic lights, like Slack or VS Code, with the CSS variables of the overlay title bar: see below). SetChromeless(false) brings the style back |
SetTitleBarOverlayColor(byte, byte, byte, byte) / ResetTitleBarOverlayColor() |
Color of the overlay title bar buttons, over the page's CSS |
SetTitleBarOverlay(bool) |
Windows, Linux: the page extends to the top of the window, under minimize, maximize and close buttons drawn by Rustino, like VS Code (see below) |
SetTitleBarOverlayHeight(int) |
Height of the overlay title bar in logical pixels (0: the platform's, 32 on Windows, 40 on Linux, 28 on macOS); on macOS it centers the traffic lights |
SetMacTrafficLightPosition(double, double) |
macOS: position of the traffic lights, in logical pixels, over the centering of SetTitleBarOverlayHeight |
SetDesktopFileName(string) |
Linux: .desktop file of the app, for the dock badge and progress |
SetDragRegionsEnabled(bool) |
Pre-run: drag regions and edge resizing from the page (on by default, see below) |
DragWindow() / DragResizeWindow(ResizeDirection) |
Move or resize the window with the mouse (call them while the left button is down) |
| Event | Args | Description |
|---|---|---|
ThemeChanged |
WindowTheme |
The theme changed, by the system or by SetTheme |
ScaleFactorChanged |
ScaleFactorChangedEventArgs |
The window moved to a monitor with another scale (.ScaleFactor, .Width, .Height) |
UrlsOpened |
string[] |
Deep links routed by AttachDeepLinks (all platforms); on macOS also files and URLs opened through the app bundle (file associations and URL schemes) |
Reopened |
bool |
macOS: Dock icon clicked; false when no window is visible, e.g. hidden in the tray |
Each event also has an observable: WhenThemeChanged, WhenScaleFactorChanged, WhenUrlsOpened, WhenReopened.
On Linux with the X11 backend WebKitGTK restyles the page when the theme changes, but doesn't fire the change event of matchMedia('(prefers-color-scheme: dark)'): scripts that need to know should listen to ThemeChanged instead.
Drag regions for chromeless windows
The elements with data-rustino-drag-region move the window, and a double click maximizes it. The attribute applies to the element itself, not to its children, so the buttons of a custom title bar stay clickable:
<header data-rustino-drag-region>
<span data-rustino-drag-region>My App</span>
<button onclick="window.ipc.postMessage('close')">✕</button>
</header>
On Windows and Linux the page covers the resize borders of chromeless windows: its outer 6 pixels resize the window instead. macOS keeps its own resize borders. With MacTitleBarStyle.Overlay the page's title bar needs the attribute too.
Overlay title bar
SetTitleBarOverlay(true) removes the native title bar and draws the minimize, maximize and close buttons over the page, in the top corner, like VS Code: Windows 11 caption buttons on Windows, GNOME round buttons on Linux (placed and filtered by the GTK gtk-decoration-layout setting). The buttons follow SetMinimizable, SetMaximizable, SetClosable and SetResizable, turn into restore when the window is maximized and go away in fullscreen; close raises Closing like the native button. The window keeps resizing from the page's edges, as a chromeless window.
On macOS SetMacTitleBarStyle(MacTitleBarStyle.Overlay) does the same with the native traffic lights, on the left.
The page lays out its own title bar in the room left by the buttons, with CSS variables set on <html> only while the buttons show, on every platform (on macOS --rustino-window-controls-left is the room of the traffic lights, and --rustino-window-controls-right is not set):
header {
height: var(--rustino-titlebar-height, 32px); /* SetTitleBarOverlayHeight, by default 32px on Windows, 40px on Linux, 28px on macOS */
padding-left: var(--rustino-window-controls-left, 0px);
padding-right: var(--rustino-window-controls-right, 0px);
}
The safe area of the title bar, the strip free of buttons, has the variables of the web's Window Controls Overlay (env(titlebar-area-*)): --rustino-titlebar-area-x, --rustino-titlebar-area-y, --rustino-titlebar-area-width and --rustino-titlebar-area-height, for content placed there directly:
.search {
position: fixed;
left: var(--rustino-titlebar-area-x, 0px);
top: var(--rustino-titlebar-area-y, 0px);
width: var(--rustino-titlebar-area-width, 100%);
height: var(--rustino-titlebar-area-height, 32px);
}
SetTitleBarOverlayHeight(48) makes the title bar taller, for instance for tabs or a search box: on Windows the buttons stretch to the new height, like the caption buttons of VS Code, on Linux the round buttons stay centered, on macOS the traffic lights are centered, as far from the left edge as from the top, and the variables follow. SetMacTrafficLightPosition places the traffic lights elsewhere, and the variables follow them.
The buttons are black or white after prefers-color-scheme (the theme of the window, see SetTheme), not after the page's colors: a page with its own palette sets --rustino-window-controls-color in its CSS, and SetTitleBarOverlayColor sets one from the host, over the CSS and across page loads (handy with Blazor Hybrid); ResetTitleBarOverlayColor goes back to the page's. Their tooltips and accessible names are in the language of the OS: the labels of the window's system menu on Windows, GTK's translations on Linux. They need drag regions (SetDragRegionsEnabled). On Windows 11 hovering the maximize button opens the Snap Layouts flyout, like a native title bar: Rustino puts a transparent native window over the button, which follows its position and size (page CSS and zoom included), so the mouse on the button is seen by Windows rather than by the page. On macOS SetTitleBarOverlay is ignored, and the traffic lights keep the system's colors.
The variables above are set by Rustino, on <html> as inline styles: the page reads them, and changes the height with SetTitleBarOverlayHeight, not by overriding them. The look of the buttons drawn on Windows and Linux is the page's instead, with these variables, set on :root or on rustino-window-controls (each falls back to the platform's look):
| Variable | Windows default | Linux default |
|---|---|---|
--rustino-window-controls-color |
black, white in dark theme | black, white in dark theme |
--rustino-window-controls-button-width / -button-height |
46px / 100% |
24px / 24px |
--rustino-window-controls-button-radius |
0 |
50% |
--rustino-window-controls-gap / -padding (sides) |
0px / 0px |
12px / 8px |
--rustino-window-controls-icon-size |
10px |
16px |
--rustino-window-controls-font (icon font) |
'Segoe Fluent Icons', 'Segoe MDL2 Assets' |
— (SVG icons) |
--rustino-window-controls-background |
transparent |
10% of the color |
--rustino-window-controls-hover-background / -active-background |
20% / 30% grey | 15% / 30% of the color |
--rustino-window-controls-close-hover-background / -close-hover-color |
#c42b1c / #fff |
as the other buttons |
--rustino-window-controls-disabled-opacity |
.35 |
.35 |
:root {
--rustino-window-controls-color: #e0e0e0;
--rustino-window-controls-button-width: 40px;
--rustino-window-controls-icon-size: 12px;
}
On Windows the icons are the glyphs of the Segoe icon fonts (U+E921 minimize, U+E922 maximize, U+E923 restore, U+E8BB close): --rustino-window-controls-font replaces the font, for instance with an @font-face of the page that has its own glyphs at those code points, and the icons keep the color of the button.
@font-face { font-family: 'My Caption Icons'; src: url('/fonts/caption-icons.woff2'); }
:root {
--rustino-window-controls-font: 'My Caption Icons';
--rustino-window-controls-icon-size: 12px;
}
For anything else the buttons are CSS parts: ::part(button) for all of them, ::part(minimize), ::part(maximize), ::part(close), ::part(restore) for maximize while the window is maximized, and ::part(icon) for the glyph or the SVG. Parts take :hover, :active, :focus-visible and :disabled, and the page's rules win over the built-in ones:
rustino-window-controls::part(button) { transition: background .1s; }
rustino-window-controls::part(close):hover { background: #e81123; }
rustino-window-controls::part(restore) { opacity: .8; }
On Windows the mouse on maximize reaches the Snap Layouts window, not the page, so :hover and :active don't apply to that button: while it's hovered or pressed it gets the parts snap-hover and snap-pressed instead, to style alongside the pseudo-classes:
rustino-window-controls::part(maximize):hover,
rustino-window-controls::part(maximize snap-hover) { background: #0078d4; }
The variables are CSS pixels and follow the page zoom (SetZoom, zoom hotkeys): on macOS, where the traffic lights don't zoom with the page, a zoomed out page gets larger values and a zoomed in one smaller ones, so the room stays the same on screen.
On macOS 26 the traffic lights of an app look like those of the system apps (larger and further apart, 23 points from one to the next instead of 20) only when its executable was linked with the macOS 26 SDK. The executables of .NET apps are the dotnet host or the app's apphost, which Microsoft links with an older SDK (15.5 up to .NET 11), so macOS shows them the traffic lights of macOS 15. Rustino measures the traffic lights, so the variables fit either look. Setting the SDK version in the apphost after publishing gives the new look, a trick that works but that Microsoft doesn't support: macOS then applies all the behavior meant for apps built for macOS 26, not only the new traffic lights, so test the app with it. Run it before code signing, which it invalidates, keeping the minimum macOS version of the apphost (minos in vtool -show-build: 12.0 on .NET 10, 14.0 on .NET 11):
vtool -set-build-version macos 12.0 26.0 -replace -output MyApp.app/Contents/MacOS/MyApp MyApp.app/Contents/MacOS/MyApp
vtool -show-build MyApp.app/Contents/MacOS/MyApp # sdk 26.0
The drag region script talks to the native side with window.ipc.postMessage messages that start with __rustino: (like the print script on Windows and macOS, see Webview): they never reach WebMessageReceived, so don't use that prefix for your own messages. Any page loaded in the window can send them, and so move, resize, maximize, minimize or close it: if the window shows untrusted pages, call SetDragRegionsEnabled(false) before WaitForClose() (no script, and the __rustino: messages reach WebMessageReceived like the others, except __rustino:print, which only prints).
Tray apps on macOS
A click on the Dock icon raises Reopened: show the window again when it was hidden in the tray.
window.Reopened += (_, hasVisibleWindows) =>
{
if (!hasVisibleWindows) window.SetVisible(true).Focus();
};
Webview
Options and events that make the page behave like an app rather than a browser:
window
.SetContextMenuEnabled(false) // no browser menu on right click
.SetBrowserControlsEnabled(false) // Windows: no F5, Ctrl+R, Ctrl+F, Ctrl+P
.SetScrollBarStyle(ScrollBarStyle.FluentOverlay) // Windows 11 scroll bars
.SetFileDropEnabled(true);
// Files dropped on the window, with their full paths (HTML5 drag and drop only gives the names)
window.FileDrop += (_, e) =>
{
if (e.Type == FileDropEventType.Drop)
OpenFiles(e.Paths);
};
// The page's <title> in the title bar
window.DocumentTitleChanged += (_, title) => window.SetTitle(title);
// Downloads: by default the user chooses where to save each file in the native save dialog
window.DownloadStarting += (_, e) =>
{
if (e.Url.EndsWith(".exe")) e.Cancel = true; // refuse it
else if (saveToDownloads) e.DestinationPath = e.SuggestedPath; // save without asking
};
window.DownloadCompleted += (_, e) => Console.WriteLine(e.Success ? $"Saved {e.Path}" : $"Not saved: {e.Url}");
Without SetContextMenuEnabled(false) right click opens the browser's menu. On macOS and Linux turning it off adds an init script that prevents the default of contextmenu events: the page still gets them, e.g. to call ShowContextMenu. SetBrowserControlsEnabled(false) leaves the menu accelerators and the page's own shortcuts working; WKWebView and WebKitGTK have no browser shortcuts.
File drop. With SetFileDropEnabled(true), FileDrop reports Enter (with the paths), Over, Drop (with the paths) and Leave; positions are in logical (CSS) pixels from the top-left corner of the page. The page doesn't get the dropped files, and the webview doesn't navigate to them. Drags that carry no files (e.g. elements dragged within the page) stay with the page on macOS and Linux; on Windows the webview stops receiving drops altogether, so the page's HTML5 drag and drop doesn't work while file drop is on (a WebView2 limitation of wry).
Downloads. DownloadStarting runs before the file is written: SuggestedPath is where a browser would save it (the Downloads folder, with a name that doesn't replace an existing file). Leave DestinationPath null to let the user choose in the save dialog (modal for the window), set it to save there without asking (an existing file is replaced), or set Cancel. Don't show dialogs from this handler. The file is downloaded to a temporary folder and moved to its destination when complete, so the save dialog can stay open while it downloads. When it can't be moved there (e.g. the disk is full), a file already at the destination is left as it was, and the window's logger reports where the download is kept until the app exits. DownloadCompleted reports every download that DownloadStarting let through: Path is null when the download failed or the user canceled the dialog. Without these events WKWebView wouldn't download at all; WebView2 no longer shows its download bar, nor asks before a page downloads more than one file. WKWebView and WebKitGTK start only the last of several downloads that the same script starts (e.g. consecutive click() calls on <a download> links): let a moment pass between them, e.g. with setTimeout.
Cookies. GetCookies() returns all the cookies, GetCookies(url) those sent to that URL; SetCookie adds or replaces a cookie (same name, domain and path), DeleteCookie removes it. RustinoCookie has Name, Value, Domain, Path, Expires, Secure, HttpOnly and SameSite (Strict, Lax, None):
window.SetCookie(new RustinoCookie("session", token) { Domain = "example.com", Path = "/", Secure = true, HttpOnly = true });
var session = window.GetCookies("https://example.com/").FirstOrDefault(c => c.Name == "session");
On Windows, WebView2 applies SetCookie and DeleteCookie a moment later: a GetCookies right after them can still return the previous cookies. On Windows, GetCookies also can't run within a webview event (WebMessageReceived, Navigating, PageLoaded, ...), where it throws InvalidOperationException: WebView2 answers only after the event returns. Call it afterwards, e.g. var cookies = await Task.Run(() => window.GetCookies()); in an async handler.
Printing. Print() and the page's window.print() open the system print dialog on every platform. On Windows and macOS an init script sends window.print() to it: WebView2 would show its print preview inside the window, cut by small windows (the system dialog of Windows has no preview), and WKWebView would do nothing.
Developer tools. With SetDevToolsEnabled(true), right click › Inspect (and F12 on Windows) open the web inspector, and so does OpenDevTools(): in its own window on Windows, docked in the window on Linux. On macOS the inspector inside the app needs a private WebKit API, which can get an app rejected from the Mac App Store, so the native library includes it only when built with the devtools feature (see Building from Source). Without it, SetDevToolsEnabled(true) makes the page inspectable from Safari's Develop menu (macOS 13.3 or later), while OpenDevTools() and CloseDevTools() do nothing.
State Queries
| Property | Description |
|---|---|
IsMinimized |
Whether the window is minimized |
IsMaximized |
Whether the window is maximized |
IsFullscreen |
Whether the window is in fullscreen |
GetPosition() |
Returns (X, Y) position |
GetSize() |
Returns (Width, Height) size |
GetMonitors() |
Returns all connected MonitorInfo[] |
GetCurrentMonitor() |
Returns MonitorInfo? for the monitor containing the window |
GetCursorPosition() |
Returns the cursor's (X, Y) on the screen in physical pixels, null before the window runs |
Events
| Event | Args | Description |
|---|---|---|
WindowClosing |
CancelEventArgs |
Fired before close (set Cancel = true to prevent) |
WindowClosed |
EventArgs |
Fired after the window is destroyed |
UnhandledCallbackException |
NativeCallbackExceptionEventArgs |
A handler, observable observer, or logger threw while Rustino.Native was calling into .NET (.CallbackName, .Exception) |
SizeChanged |
SizeEventArgs |
Fired on resize (.Width, .Height) |
LocationChanged |
PointEventArgs |
Fired on move (.X, .Y) |
FocusChanged |
bool |
Fired on focus/blur |
WebMessageReceived |
string |
Fired when JS calls window.ipc.postMessage(msg) |
WebMessageReceivedWithSource |
WebMessageEventArgs |
Same messages with the sending page's URL (.Message, .SourceUrl): check it if the webview can navigate to other sites |
PageLoaded |
PageLoadEventArgs |
Fired on page load start/finish (.IsStarted, .Url) |
Navigating |
NavigationEventArgs |
Fired before navigation (.Url, set Cancel = true to block) |
MenuItemClicked |
string |
Fired when a menu item is clicked (the item's ID) |
MenuItemCheckedChanged |
MenuItemCheckedEventArgs |
Fired after MenuItemClicked when the user toggles a check item (.Id, .IsChecked) |
TrayIconClicked |
TrayIconClickedEventArgs |
Fired once per click on the tray icon (.Button, .X, .Y); never on Linux |
GlobalShortcutPressed |
string |
A global shortcut of the window was pressed (the accelerator as registered) |
MonitorsChanged |
MonitorsChangedEventArgs |
A monitor was added, removed or changed (see Monitors) |
FileDrop |
FileDropEventArgs |
Files dragged over the window and dropped, with their full paths (.Type, .Paths, .X, .Y); needs SetFileDropEnabled(true) |
DocumentTitleChanged |
string |
The page's <title> changed |
DownloadStarting |
DownloadStartingEventArgs |
A download starts (.Url, .SuggestedPath; set .DestinationPath or .Cancel) |
DownloadCompleted |
DownloadCompletedEventArgs |
A download ended (.Url, .Path, .Success) |
Exceptions thrown from a native callback are caught before they can cross the Rust/.NET boundary. Rustino logs
them through the configured ILogger and raises UnhandledCallbackException; exceptions thrown by that event
are also caught. A closing-handler exception allows the window to close, a navigation-handler exception allows
the navigation, and a download-starting exception cancels the download. A custom-scheme handler exception leaves
the response empty, which Rustino returns as HTTP 404.
Observable Streams (IObservable<T>)
All events are also available as IObservable<T> properties for reactive programming (no System.Reactive dependency required):
| Property | Type | Description |
|---|---|---|
WhenSizeChanged |
IObservable<(int Width, int Height)> |
Size change stream |
WhenLocationChanged |
IObservable<(int X, int Y)> |
Position change stream |
WhenFocusChanged |
IObservable<bool> |
Focus/blur stream |
WhenWebMessageReceived |
IObservable<string> |
JS message stream |
WhenWebMessageReceivedWithSource |
IObservable<WebMessageEventArgs> |
JS message stream with the sending page's URL |
WhenPageLoaded |
IObservable<PageLoadEventArgs> |
Page load stream |
WhenNavigating |
IObservable<NavigationEventArgs> |
Navigation stream |
WhenWindowClosed |
IObservable<EventArgs> |
Window closed stream |
WhenMenuItemClicked |
IObservable<string> |
Menu item click stream |
WhenMenuItemCheckedChanged |
IObservable<MenuItemCheckedEventArgs> |
Check item toggle stream |
WhenTrayIconClicked |
IObservable<TrayIconClickedEventArgs> |
Tray icon click stream |
WhenGlobalShortcutPressed |
IObservable<string> |
Global shortcut stream |
WhenMonitorsChanged |
IObservable<MonitorsChangedEventArgs> |
Monitor changes stream |
WhenFileDrop |
IObservable<FileDropEventArgs> |
File drag and drop stream |
WhenDocumentTitleChanged |
IObservable<string> |
Document title stream |
WhenDownloadStarting |
IObservable<DownloadStartingEventArgs> |
Download start stream |
WhenDownloadCompleted |
IObservable<DownloadCompletedEventArgs> |
Download end stream |
All streams complete automatically when the window closes or is disposed.
Rustino.NET.Reactive (companion package)
For System.Reactive operators, add the EdoardoTona.Rustino.Reactive package:
using System.Reactive.Linq;
using Rustino.NET.Reactive;
// Throttled resize
window.WhenSizeChangedThrottled(TimeSpan.FromMilliseconds(200))
.Subscribe(size => Console.WriteLine($"{size.Width}x{size.Height}"));
// Message routing by prefix
window.WhenWebMessageWithPrefix("cmd:")
.Subscribe(cmd => HandleCommand(cmd));
// Page load completion only
window.WhenPageLoadCompleted()
.Subscribe(e => Console.WriteLine($"Loaded: {e.Url}"));
// Throttled move events
window.WhenLocationChangedThrottled(TimeSpan.FromMilliseconds(100))
.Subscribe(pos => Console.WriteLine($"Moved to {pos.X},{pos.Y}"));
// Distinct focus changes
window.WhenFocusChangedDistinct()
.Subscribe(focused => Console.WriteLine($"Focus: {focused}"));
Blazor Hybrid (Rustino.Blazor)
The EdoardoTona.Rustino.Blazor package hosts Razor components in a Rustino window, like Photino.Blazor. Components run in .NET and render into the native webview; the app is served from app://localhost/.
using Rustino.Blazor;
var builder = RustinoBlazorAppBuilder.CreateDefault(args);
builder.Services.AddSingleton<MyService>(); // regular dependency injection
builder.RootComponents.Add<App>("#app");
var app = builder.Build();
app.MainWindow.SetTitle("My Blazor App"); // the underlying RustinoWindow
app.Run();
When the main window closes, Run() disposes the app: the components and scoped services of each window (their
Dispose/DisposeAsync run), then the app's services. An app built but never run is disposed with
Dispose()/DisposeAsync().
Use the Microsoft.NET.Sdk.Razor SDK and put a host page in wwwroot/index.html:
<!DOCTYPE html>
<html>
<head>
<base href="/" />
</head>
<body>
<div id="app">Loading…</div>
<script src="_framework/blazor.webview.js"></script>
</body>
</html>
Inside components:
@inject RustinoWindow Windowgives access to the whole native API (dialogs, notifications, menus, window state, …).- Native events (
SizeChanged,MenuItemClicked, …) are raised outside Blazor's dispatcher: update state withInvokeAsync(StateHasChanged). IJSRuntimeand[JSInvokable]work as in any Blazor app.@inject HttpClient Httpreads app files (e.g.Http.GetStringAsync("data.json"); missing files are404 Not Found) and forwards other requests to the network.- Only the app's own pages (
app://localhost/) can talk to the components: messages from other sites the webview navigates to, or from frames of other origins embedded in the app, are ignored.
Static files come from wwwroot next to the executable (published apps) or from the project during development. Pass an IFileProvider to CreateDefault to serve them from somewhere else (e.g. embedded resources).
Multiple windows
OpenWindow<TComponent> opens another window with the same host page and renders a root component in it. Inject RustinoBlazorApp to call it from a component:
@inject RustinoBlazorApp App
<button @onclick="OpenDetails">Details</button>
@code {
private void OpenDetails() =>
App.OpenWindow<Details>(
"#app",
new Dictionary<string, object?> { [nameof(Details.Id)] = 42 }, // root component parameters
window => window.SetTitle("Details").SetSize(600, 400));
}
The window shares the app's singleton services, while scoped services are per window. Its components that inject RustinoWindow get the new window, not the main one. Scoped services are different: the container resolves RustinoWindow in their constructors to the main window. Have them inject RustinoWindowAccessor and use its Window, which is the window of their page in every window, the main one included:
builder.Services.AddScoped<EditorService>();
public class EditorService(RustinoWindowAccessor accessor)
{
public void Close() => accessor.Window.Close(); // the window of this page
}
It closes when the user closes it, with Close() on the returned RustinoWindow, or when the main window closes. When the window can't open (e.g. its webview fails), RustinoBlazorApp.WindowFailed is raised with the window and the exception, and the window is disposed. Call it while Run() runs; see Multiple Windows for how the windows share the event loop.
See samples/Rustino.Samples.Blazor for a complete example.
Building from Source
Prerequisites
- Rust toolchain (1.90+)
- .NET SDK (10.0+)
- Windows: WebView2 runtime (pre-installed on Windows 10/11)
- macOS: Xcode Command Line Tools
- Linux:
libgtk-3-dev libwebkit2gtk-4.1-dev
Build
# Build the Rust native library
cd src/Rustino.Native
cargo build --release
# ...or, on macOS, with the web inspector inside the app (private WebKit API, see Developer tools)
cargo build --release --features devtools
cd ../..
# Build the .NET projects of Rustino.slnx: packages, tests and samples
dotnet build
# Run a sample
dotnet run --project samples/Rustino.Samples
# Run the Blazor sample
dotnet run --project samples/Rustino.Samples.Blazor
Repository layout
| Path | Content |
|---|---|
src/Rustino.Native |
The native library (Rust). Each feature is a module that keeps its C API (rustino_*) next to its implementation; window holds the window and the event loop |
src/Rustino.NET |
The .NET wrapper: Interop/ (the P/Invoke declarations of the C API), Window/ (RustinoWindow, one partial file per area, and its types), SingleInstance/ |
src/Rustino.NET.Reactive, src/Rustino.Blazor |
The packages built on Rustino.NET |
tests/ |
The .NET tests, with the interop contract tests |
samples/ |
The sample apps |
Directory.Build.props holds the settings shared by the .NET projects (src/Directory.Build.props adds the
version and the metadata of the packages) and Directory.Packages.props the version of every NuGet dependency.
Samples
samples/Rustino.Samples: a tabbed showcase of the window API — window state and chrome, JS interop, dialogs and message boxes, menus and tray, notifications, badges, monitors, reactive streams, native window features, webview (downloads, file drop, cookies, printing, devtools) and, in the Launch tab, single instance, deep links,Activate()andOpenExternal(). Run it a second time, e.g.dotnet run -- rustino-sample://open?id=42, to see the launch forwarded to the first process.samples/Rustino.Samples.Blazor: Blazor Hybrid with theapp://custom scheme, dependency injection,HttpClientand other windows that share a singleton service with the main one.
Interop contract tests
The .NET tests compare every Rust C export with the P/Invoke imports, including callback signatures and platform
gating. They also compare the #[repr(C)] layouts with the Rust-generated snapshot and check that each import
exists in the built native library for the current platform:
dotnet test tests/Rustino.NET.Tests -c Release
On Windows, MultiWindowTests (and the Rust test windows_started_while_the_app_runs_join_its_event_loop) open
hidden windows, so they need a desktop session and the WebView2 Runtime. tests/Rustino.Blazor.Tests covers the
services of the Blazor windows.
Build src/Rustino.Native with cargo build --release first to enable the binary export check. The Rust ABI
snapshot is checked by cargo test --release; after an intentional ABI layout change, update it with:
cd src/Rustino.Native
UPDATE_ABI_SNAPSHOT=1 cargo test --release abi_layout
Releasing
.github/workflows/release.yml builds the native library for the six platforms,
packs the three packages and pushes them to NuGet.org through trusted publishing (a short-lived key obtained with GitHub OIDC; the NUGET_USER secret holds the nuget.org profile name). It runs when a GitHub
release is published (the version is the tag without the leading v, e.g. v0.4.0 → 0.4.0) and attaches the
packages to the release; a manual run asks for the version to publish.
Cross-Platform Support
| Platform | WebView Engine | Native Library |
|---|---|---|
| Windows x64/ARM64 | WebView2 (Chromium) | rustino_native.dll |
| macOS x64/ARM64 | WKWebView (WebKit) | librustino_native.dylib |
| Linux x64/ARM64 | WebKitGTK | librustino_native.so |
License
MIT — see LICENSE. Based on Rustino by Ivy Interactive.
Inspired by and API-compatible with Photino, originally created by TryPhotino (Apache-2.0).
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.14)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on EdoardoTona.Rustino:
| Package | Downloads |
|---|---|
|
EdoardoTona.Rustino.Blazor
Blazor Hybrid for Rustino.NET: host Razor components in a native Rustino window. Drop-in replacement for Photino.Blazor. |
|
|
EdoardoTona.Rustino.Reactive
System.Reactive extensions for Rustino.NET window events. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.6.0-preview.3 | 59 | 11/9/2026 |
| 0.6.0-preview.2 | 77 | 10/31/2026 |
| 0.6.0-preview.1 | 71 | 10/31/2026 |
| 0.5.6 | 116 | 11/10/2026 |
| 0.5.5 | 109 | 11/9/2026 |
| 0.5.4 | 131 | 11/5/2026 |
| 0.5.3 | 111 | 11/5/2026 |
| 0.5.1 | 137 | 11/1/2026 |
| 0.5.0 | 131 | 10/31/2026 |
| 0.4.4 | 120 | 10/31/2026 |
| 0.4.2 | 164 | 9/29/2026 |
| 0.4.1 | 130 | 9/28/2026 |
| 0.4.0 | 121 | 9/28/2026 |