Windows WPF UI Shell
Overview
The Windows UI shell is the net10.0-windows WPF executable under v2rayN/v2rayN/. v2rayN/v2rayN/v2rayN.csproj enables WPF, sets the application icon and manifest, embeds the tray/app icons, references ServiceLib, and brings in MaterialDesignThemes, H.NotifyIcon.Wpf, and ReactiveUI.WPF. The manifest at v2rayN/v2rayN/app.manifest opts into Windows common controls v6, while v2rayN/v2rayN/App.xaml defines process-wide Material Design resources, standard font-size resources, global WindowGlobal/ViewGlobal styles, and converters used by the XAML.
Startup is in v2rayN/…/App.xaml.cs. OnStartup enforces a single instance with an EventWaitHandle keyed by the executable path hash; a second launch signals the first instance and exits unless the Global.RebootAs argument is present. The first instance initializes shared application state through AppManager.Instance.InitApp() and InitComponents(), installs the WPF WindowDialog implementation into AppManager.Instance.WindowDialog, builds ReactiveUI for WPF, constructs a shared ServiceLib.ViewModels.MainWindowViewModel, resolves its view through SimpleViewLocator, and shows MainWindow. Unhandled dispatcher, AppDomain, and task exceptions are logged via Logging.SaveLog; OnExit logs and kills the current process after WPF shutdown.
The view locator in v2rayN/…/SimpleViewLocator.cs is the bridge from shared ServiceLib.ViewModels to WPF classes. It maps each view model type to a concrete Views/* class, including MainWindow, the profile/status/message/clash views, and all settings/edit dialogs. v2rayN/…/ViewHost.cs uses this locator to inject child view instances into ContentControls whenever the main view model swaps child view models. v2rayN/…/WindowBase.cs is the base for dialog windows; it restores window size from ConfigTextHandler.GetWindowSizeItem(GetType().Name) on load and saves width/height back through ConfigTextHandler.SaveWindowSizeItem on close.
v2rayN/v2rayN/Views/MainWindow.xaml is the shell layout. It hosts a Material Design DialogHost named RootDialog, toolbar menus for server, subscription, settings, help, reload, promotion, and close actions, a theme popup, a status-bar content host, and three alternative main layouts: horizontal split, vertical split, and tabbed navigation. v2rayN/…/MainWindow.xaml.cs binds toolbar items to commands exposed by MainWindowViewModel, wires Windows-only interactions for clipboard import, QR/screen scan, image browsing, show/hide, snackbars, app-exit storage, and shutdown, and chooses the active layout from ViewModel.MainGirdOrientation. It persists split sizes into ConfigTextHandler.SaveMainGirdHeight, hides rather than closes on Closing, restores from the single-instance event by calling ShowHideWindow(true), and registers global hotkeys through WindowsManager.Instance.RegisterGlobalHotkey. StatusBarView is hosted by MainWindow and supplies the tray icon/menu plus proxy/routing/server controls.
Most application behavior lives in shared ServiceLib view models; the WPF shell supplies bindings and platform services. v2rayN/…/ProfilesView.xaml.cs binds profile and subscription collections, implements grid column persistence, drag/drop sorting, keyboard shortcuts, clipboard export, save-file dialogs, QR sharing, and focus/dispatcher interactions for ProfilesViewModel. ProfilesSelectWindow provides the same grid affordances for profile-picking workflows and exposes SetConfigTypeFilter to callers. MsgView appends streamed messages into a text box with filter/auto-refresh bindings and copy/clear commands. ClashProxiesView binds Clash proxy groups/details and rule mode controls; ClashConnectionsView binds Clash connection rows, closes connections through commands, and persists connection grid column widths under Config.ClashUIItem.ConnectionsColumnItem.
Settings and edit windows are thin WPF adapters over shared view models. AddServerWindow switches visible protocol/transport/TLS/Reality panels based on SelectedSource.ConfigType, binds protocol-specific fields for VMess, VLESS, Shadowsocks, SOCKS/HTTP, Trojan, Hysteria2, TUIC, WireGuard, AnyTLS, Naive, and MASQUE, and drives transport panel visibility from network/header selections. AddServer2Window handles custom config and custom outbound profiles and uses UI.OpenFileDialog for external config selection. OptionSettingWindow binds inbound, proxy, TUN, speed-test, core-type, UI, and source URL settings; it also enumerates custom fonts from Utils.GetFontsPath() and writes selected PAC paths from a Windows file picker. DNSSettingWindow, FullConfigTemplateWindow, RoutingSettingWindow, RoutingRuleSettingWindow, RoutingRuleDetailsWindow, SubSettingWindow, SubEditWindow, and GlobalHotkeySettingWindow bind their corresponding shared view models, fill combo/check-list controls from Global option lists, and translate WPF events such as multi-selection, double-click, select-all, browse-file, read/write clipboard, QR share, and confirmation dialogs into ReactiveUI interactions or direct view model calls.
Windows-specific managers and helpers live under v2rayN/v2rayN/Manager/ and v2rayN/v2rayN/Common/. WindowsManager chooses tray icons from the default routing custom icon, a local NotifyIcon{n}.ico override in the app path, or embedded Properties.Resources.NotifyIcon{n}; it also exposes the app icon image and delegates global hotkey registration. HotkeyManager reads ConfigTextHandler.Config.GlobalHotkeys, registers OS-wide hotkeys with RegisterHotKey, intercepts WM_HOTKEY via ComponentDispatcher.ThreadPreprocessMessage, and either raises HotkeyTriggerEvent or, while the global hotkey settings window is open, replays the key to the focused WPF element. WindowDialog implements ServiceLib.Base.IWindowDialog by resolving a view model to a WindowBase<TViewModel>, setting Application.Current.MainWindow as owner, wiring ICloseable.RequestClose to DialogResult = true, and returning the modal result.
WindowsUtils wraps clipboard access, DWM dark title-bar border calls, app/tray icon conversion, and detection of the current Windows app theme from the registry. QRCodeWindowsUtils converts shared QR-code bytes into WPF ImageSources and captures the working area of the screen for QR scanning, accounting for DPI through a window handle. UI centralizes WPF message boxes and Win32 open/save file dialogs. MaterialDesignFonts resolves a configured font family from the app fonts directory and falls back to Microsoft YaHei; InverseBooleanConverter and DelayColorConverter support XAML bindings. MyDGTextColumn adds an ExName metadata field used by profile and Clash grids to persist column order/width.
Theme state is the one UI-specific view model in this module. v2rayN/…/ThemeSettingViewModel.cs reads ConfigTextHandler.Config.UiItem, applies Material Design base theme and primary color via PaletteHelper, updates WPF resource font sizes (StdFontSize, StdFontSize1, StdFontSize-1), sets the main window DWM border through WindowsUtils.SetDarkBorder, saves config changes reactively, and subscribes to SystemEvents.UserPreferenceChanged so FollowSystem themes update when Windows changes color preferences. ThemeSettingView hosts this view model in the main toolbar popup.
Resources are split between WPF resources and embedded .resx icons. App.xaml owns shared styles and default Material Design theme dictionaries. Icon files in v2rayN/v2rayN/Resources/ are included by v2rayN.csproj; Properties/Resources.resx and Properties/Resources.Designer.cs provide strongly typed System.Drawing.Icon access for tray icons, while WPF windows use pack URIs such as /Resources/v2rayN.ico and pack://application:,,,/Resources/NotifyIcon{n}.ico.
Routing / covers
This document owns the Windows WPF shell under:
v2rayN/v2rayN/**
Coupling
- If a shared
ServiceLib.ViewModelsclass is added, renamed, or moved, update v2rayN/…/SimpleViewLocator.cs and the correspondingViews/*.xaml(.cs)genericIViewFor/WindowBase<T>declarations; App.xaml.cs,ViewHost, andWindowDialogall depend on locator resolution and fail silently by returningnull/falsewhen a mapping is missing. - If a shared view model interaction is changed, update the WPF handler in the owning view: MainWindow.xaml.cs handles clipboard, QR screen scan, image browsing, show/hide, snackbars, and shutdown; ProfilesView.xaml.cs, StatusBarView.xaml.cs, RoutingRuleSettingWindow.xaml.cs, and BackupAndRestoreView.xaml.cs provide file dialogs, clipboard, confirmation dialogs, QR dialogs, icon refresh, and dispatcher work. These interactions are the platform boundary for ServiceLib workflows.
- If
Config.UiItempersistence keys or layout enums change, verify MainWindow.xaml.cs, ProfilesView.xaml.cs, ProfilesSelectWindow.xaml.cs, ClashConnectionsView.xaml.cs, WindowBase.cs, MaterialDesignFonts.cs, and ThemeSettingViewModel.cs; they read/write window sizes, split proportions, grid columns, selected font family, theme, language, and font-size resources by matching config property names and enum values. - If tray icon or system proxy states change, verify
WindowsManager.GetNotifyIcon,WindowsManager.GetAppIcon, andStatusBarView.RefreshIcon; icon selection is tied toconfig.SystemProxyItem.SysProxyType, embeddedNotifyIcon1..4resources, and optional routing custom icons fromConfigDbHandler.GetDefaultRouting(). - If global hotkey definitions or
EGlobalHotkeyordering change, update bothHotkeyManagerandGlobalHotkeySettingWindow: the settings window tags text boxes with(EGlobalHotkey)index, whileMainWindow.OnHotkeyHandlermaps proxy hotkey enum values toESysProxyTypeby subtracting one. - If Material Design or font resources are renamed, verify
App.xaml,ThemeSettingViewModel,MaterialDesignFonts, and all XAML styles usingWindowGlobal,ViewGlobal,DefButton,DefDataGrid, and font-size dynamic resources; many windows assume these keys exist at application scope.
Risks
- v2rayN/…/App.xaml.cs calls
Process.GetCurrentProcess().Kill()inOnExit; ifAppEvents.AppExitRequestedor window storage handlers do not run before shutdown, process termination can bypass remaining async cleanup after WPF begins exiting. - v2rayN/…/HotkeyManager.cs registers OS hotkeys against
nint.Zerousing the packed key/modifier value as both dictionary key and hotkey id. If two actions intentionally share the same key it groups them, but ifGlobalHotkeySettingWindowassigns an invalid duplicate or enum ordering changes, one OS registration controls multipleEGlobalHotkeyactions andMainWindow.OnHotkeyHandlermay trigger the wrong proxy mode. - v2rayN/…/SimpleViewLocator.cs uses exact runtime types in a manual dictionary. If a shared view model is subclassed or renamed without updating the locator,
ViewHost.Showleaves the host empty andWindowDialog.ShowDialogAsyncreturnsfalserather than throwing, making missing UI mappings hard to detect. - v2rayN/…/ThemeSettingViewModel.cs registers
SystemEvents.UserPreferenceChangedwith an anonymous handler and never unregisters it. Creating multipleThemeSettingViewModelinstances can accumulate callbacks that mutate WPF theme state after the original view is gone.