Sphere10.Framework.Windows.Forms
3.2.0
dotnet add package Sphere10.Framework.Windows.Forms --version 3.2.0
NuGet\Install-Package Sphere10.Framework.Windows.Forms -Version 3.2.0
<PackageReference Include="Sphere10.Framework.Windows.Forms" Version="3.2.0" />
<PackageVersion Include="Sphere10.Framework.Windows.Forms" Version="3.2.0" />
<PackageReference Include="Sphere10.Framework.Windows.Forms" />
paket add Sphere10.Framework.Windows.Forms --version 3.2.0
#r "nuget: Sphere10.Framework.Windows.Forms, 3.2.0"
#:package Sphere10.Framework.Windows.Forms@3.2.0
#addin nuget:?package=Sphere10.Framework.Windows.Forms&version=3.2.0
#tool nuget:?package=Sphere10.Framework.Windows.Forms&version=3.2.0
🖼️ Sphere10.Framework.Windows.Forms
Windows Forms UI framework and component library providing data binding controls, database connection panels, validation components, and presentation utilities for desktop applications.
Sphere10.Framework.Windows.Forms enables rapid Windows desktop application development with pre-built UI components for database connectivity, data display, user input validation, and common desktop patterns.
Source organization
Domain folders such as Application, VisualCalendar, Charts, Database,
ExplorerBar, ListMerger, Logging, RichText, ToolStrips, VisualGrid and
Wizard own their related functionality.
Their Controls folders contain reusable visual controls; their Forms folders
contain forms, dialogs and hosted screens. Nonvisual contracts, settings, builders
and helpers remain with the domain. A control or form with dedicated support
classes receives its own domain; apply that rule to Misc and the general visual
folders alike. Standalone general controls live in Controls, and general dialogs
and forms in Forms. Cross-domain helpers belong in Misc; extension classes
belong in Extensions or their owning domain's Extensions. Existing CLR
namespaces and persisted control identities are independent of these locations.
📦 Installation
dotnet add package Sphere10.Framework.Windows.Forms
Domains
Every folder of Sphere10.Framework.Windows.Forms is a domain with its own README, which lists all of its public types.
| Domain | What it provides | Source |
|---|---|---|
| Attachment | Compact file/clipboard attachment selection with a modal editor and immutable content snapshots. | source |
| Application | Native WinForms application shell with plugins, blocks, menus, hosted screens, main forms, Options dialogs and startup integration. | source |
| VisualCalendar | Scheduling grid control that shows appointments in named columns over a day, a week or a month, with selection, drag-and-drop rescheduling and resizing, a data source that shows ICalendar<string, Color, string> objects and an editor for recurrence rules. |
source |
| Authentication | Modal logon and password-entry dialogs that delegate credential checks and password policy to caller-supplied callbacks. | source |
| Charts | Designer-editable numeric and telemetry chart controls over captured data, with a shared Log Output workflow for chart observations. | source |
| ComboBoxes | Combo box controls with placeholders and validation, custom drop-down content, enum binding and image tile choices. | source |
| Controls | Standalone general-purpose WinForms controls for text, numeric, color, image, button, group box and panel input and presentation. | source |
| Database | Database connection bars and panels that switch their editor by DBMS type and produce an IDAC, plus a form that runs a SQL script. |
source |
| Dialogs | Awaitable message, question and exception dialogs with up to five custom buttons and a remembered "always" answer. | source |
| Display | Monitor arrangement control that draws the desktop's displays as selectable tiles, in the style of Windows display settings. | source |
| Drawing | Measurable, cloneable visual elements for owner-drawn cells and controls, with draw-style enums, graphics measurement and layered transparent forms. | source |
| DropDown | Popup and drop-down hosting for custom editor content, with working-area placement, resize grips and a themed drop-down button. | source |
| ExplorerBar | Windows XP style explorer bar with collapsible, animated task groups and link-style task items, plus its theme settings and serialization surrogates. | source |
| Extensions | Extension methods for WinForms controls, forms and tool strip items, service registration helpers for native applications, and the Tools.WinForms and scope entry points. |
source |
| Forms | General-purpose dialogs and forms for entering text, reviewing text before saving, editing an object in a property grid and viewing text. | source |
| HexEditor | A hex editor control, window and dialogs over any seekable stream, with bounded caching, pending edits, streaming search and a data inspector. | source |
| HotKeys | System-wide keyboard shortcuts registered through RegisterHotKey, with user-assignable commands and editor controls. |
source |
| ListMerger | A two-list control whose buttons move or copy the selected items between a left and a right list. | source |
| LoadingCircle | A DPI-aware animated activity indicator for forms, tool strips and temporary overlays. | source |
| Logging | Windows Forms log views, text box loggers and an optional log output selector with a configuration wizard and remembered preferences. | source |
| Misc | Cross-domain Windows Forms helpers, including the Tools.WinForms facade, rendering deferral scopes, UI-thread disposal, placeholder text, system icon kinds and XML signatures. |
source |
| MultiSelection | A split button that offers a default action and a menu of alternative actions. | source |
| Notifications | A passive on-screen popup that confirms a state change without taking focus. | source |
| PathSelector | A text box with a browse button for choosing a file or folder path. | source |
| ProgressBar | A progress bar that draws a percentage or custom text over the bar. | source |
| Resources | Icon, image, cursor and theme files that the library embeds through its Resources class. |
source |
| RichText | An RTF value type, its conversions and an extended rich text box with underline styles, subscript, superscript and typed values. | source |
| Separator | A two-tone horizontal or vertical separator line control. | source |
| Services | A status indicator and start/stop button for one Windows service. | source |
| SourceGrid | A cell-based grid control for Windows Forms, with static and virtual grids, pluggable cell views, models, controllers and editors, selection, export and printing. | source |
| SourceGrid.Extensions | Ready-made grids built on SourceGrid for two-dimensional arrays, IBoundList data binding, read-only property sources, list editing and appointment planning. |
source |
| StateEvent | Model-aware FormEx and UserControlEx base classes and the per-control observers that turn native edits into one StateChanged notification. |
source |
| Text | Fixed-length text record parsing and writing driven by field definitions or by attributes on a record class. | source |
| ToolStrips | Tool strip, menu strip and status strip helpers for merging items into an inherited form's strips, keeping toolbar height stable, choosing a value from a toolbar button, adjusting a number with a toolbar slider, starting or stopping an operation from one command, and offering toolbar commands from menus. | source |
| Updates | The "New Version Available" notice for any update channel, and the release server's Windows updater with its BITS download, hash verification, installer launch and one-call registration. | source |
| ValidationIndicator | A small status icon control that runs asynchronous validation handlers and shows valid, error, validating or disabled state with a message tooltip. | source |
| VisualEntityEditor | Entity editing, change tracking and modal validation shared by grids and application settings. | source |
| VisualGrid | Data-source-driven grid with paging, search, sorting, row details and per-user preferences. | source |
| VisualGridDialog | Modal host for a configured VisualGrid over a borrowed source. | source |
| VisualGridDropDown | Standalone grid dropdown and shared existing-reference selection. | source |
| WindowHighlight | A click-through outline drawn over another window's physical desktop bounds, and a one-use picker that lets the user select a desktop window with the mouse. | source |
| WindowTitleBar | A small button kept beside the caption buttons of other applications' windows, with per-window images, click reporting and a menu helper. | source |
| Wizard | Windows Forms presentation of the shared application wizard, with screen base classes, a modal wizard dialog and a fluent builder. | source |
Project root
Types declared in the project folder itself:
| Type | Kind | Purpose |
|---|---|---|
ModuleConfiguration |
class | Module registration that adds default About, Report Bug, Request Feature and Send Comments dialogs, ApplicationBanner, a singleton IMachineIdentifierGenerator (WindowsMachineIdentifierGenerator with the default sources), built-in control state event providers and SessionEndingHandlerInitializer unless the application registered its own |
Chart Library Dependency
The chart controls use Sphere10.Framework.Windows.Forms.DataVisualization, which imports Microsoft's original Windows Forms charting source with the maintained fork's runtime fixes. Its licenses and third-party notices are retained. Source builds reference the project within Framework; NuGet builds use its matching Framework package. A separate charting checkout is not required.
The library builds for net10.0-windows, and also for net11.0-windows with the
.NET 11 SDK, the same targets as this project. A .NET 10 SDK builds only
net10.0-windows. Build and pack the absorbed project within Framework to check
both targets. Runtime code, enums, helpers and resources
are consolidated into one assembly; the legacy designer pipeline was removed.
Local CHM help
CHMHelpProvider opens context help on the containing form's monitor, falling
back to IUserInterfaceServices.PrimaryUIController for non-control contexts.
It preserves the CHM's navigation and window styles, uses physical coordinates
under a temporary per-monitor DPI context, and moves an existing viewer when
the requesting form changes monitors. A viewer already on that monitor keeps
its current placement; a moved maximized viewer remains maximized.
Numeric charts
GraphChart is a designer-editable numeric plotting control backed by
Sphere10.Framework.Windows.Forms.DataVisualization. Style selects line, filled area, vertical columns
or horizontal bars. BarChart provides the column-chart defaults, category
labels and margins. The Graph And Bar Charts screen in WinForms Tester demonstrates
multiple series, missing observations, styles, axes and live snapshot updates.
Supply captured data with SetSeries(GraphChartSeries[]) on the owning UI
thread. GraphChartSeries copies its GraphChartPoint[]; its Points and the
control's Series properties return detached arrays. X coordinates must be
finite; missing or nonfinite Y observations remain gaps. Line and area segments
stop at gaps, while bar charts retain missing category positions. Signed numeric
values are supported. Neither control captures data, schedules refreshes, reads
Windows counters or retains an unbounded history.
Configure MinimumX, MaximumX, MinimumY and MaximumY for explicit ranges;
null restores automatic scaling. XAxisTitle, YAxisTitle, XValueFormat and
YValueFormat control labels and units. XLabelFormatter and YLabelFormatter
allow runtime label formatting. Set ShowLegend, ShowAxes, ShowVerticalGrid,
GridColor and PlotBackColor as appropriate. A series can override the control's
style, and a point's optional Label supplies its category caption. NativeChart
exposes the owned engine for advanced configuration; the control owns disposal.
PlotBounds reports the actual layout, and TryGetPointAt returns the nearest
captured category or numeric X coordinate, including a missing observation.
Empty captures display a centered NO DATA message, including captures with
only unavailable values and after Clear. Finite zero values display normally.
NoDataText changes the message; an empty string hides it. TelemetryChart and
BarChart share the same empty-state presentation.
var chart = new BarChart { YAxisTitle = "Temperature (°C)", MinimumY = 0 };
chart.SetSeries(new[] {
new GraphChartSeries("CPU Cores", new[] {
new GraphChartPoint(0, 42, "Core 0"),
new GraphChartPoint(1, 44, "Core 1")
}, Color.Firebrick)
});
Repeated snapshots reuse the native chart control and retained series, batch
collection invalidations, and remove superseded series. Resizing only renders
captured values. Both source and package builds use
Sphere10.Framework.Windows.Forms.DataVisualization.
Telemetry history charts
TelemetryChart adapts captured time/value samples to the same GraphChart
renderer, retaining the existing telemetry API and designer layout.
Call SetSamples(TelemetryChartPoint[]) on its UI thread; input membership is
copied and the returned Points array is detached. The chart performs no sampling,
background scheduling or native inventory. The consumer owns capture cadence,
history length and statistics. All System Expert CPU, memory, GPU, network,
overview, process-inspection and temperature charts use this control.
Unit selects percent, bytes, bytes/second or Celsius scales. Celsius supports
real subzero readings and extends beyond 100 °C when necessary. Invalid and
missing observations break both line and filled-area segments; they do not become
zero readings. Select PlotStyle = TelemetryChartStyle.Area for a filled history,
and configure LineColor, FillColor, PlotBackColor, GridColor and
ShowVerticalGrid to match its host. Compact hides scale labels and headers;
ShowHeader independently hides the title/current-value header.
Hover displays the nearest captured value and local capture time, using elapsed
time rather than sample index. TryGetSampleAt exposes the same lookup in control
coordinates. Data normalization and scale labels are prepared when samples
change; native resizing and paint only project that prepared history. The
control owns its tooltip and disposes it with the surface.
TelemetryChartPoint.Context can carry immutable detached context captured with
an observation, while retaining the two-argument constructor and deconstruction.
SampleContextText adds prepared context to hover text, and left double-click
raises SampleActivated with the exact captured point. These callbacks run on
the control owner; resource queries belong in a separately awaited worker action.
The chart borrows context and releases its references when replaced, cleared or
disposed. Keep it within the caller's bounded history; do not put live resources
or native controls in point context. The Live Telemetry demo shows per-observation
context and selection, including missing-value gaps.
var chart = new TelemetryChart {
Unit = TelemetryChartUnit.Celsius,
PlotStyle = TelemetryChartStyle.Area,
LineColor = Color.Firebrick,
ShowVerticalGrid = true
};
chart.SetSamples(new[] {
new TelemetryChartPoint(DateTime.UtcNow.AddSeconds(-1), 42),
new TelemetryChartPoint(DateTime.UtcNow, 43)
});
Chart Log Output
Chart logging writes one log entry per captured moment: every reading of a sample
shares one line that carries the sample time, however many devices or series the
sample spans. ChartLogOutputBehavior.FormatSample(title, capturedAtUtc, readings)
(and Tools.WinForms.Charts.FormatLogSample) formats that line without accessing
controls or writing output. A raw sampler can format on a worker and enqueue the
line through a shared toolbar selector with includesTimestamp: true.
FormatSampleLines (and Tools.WinForms.Charts.FormatLogLines) splits a sample
into one line per device or group, where a group is the part of a series before
/ (for example GPU 0 / Temperature). Use it only when the source being logged
warrants a line per device; it is not the default. Disable chart capture when that sampler supplies
the shared output, so repainting retained history does not duplicate records.
Register LogOutputLifetime as an application-owned singleton when outputs must
drain during application shutdown. Register each owner and its asynchronous close
callback through Register or RegisterCurrent, and await CompleteAsync in the
application finalizer on the owning UI dispatcher. Closing an owner removes its
registration immediately; only unfinished accepted writes remain tracked until
they complete. The component tester and System Expert share this implementation.
Right-click a GraphChart, BarChart or TelemetryChart, including its empty
surface, and choose Log Output. The command uses the shared
LogOutputSelectorControl wizard and configuration dialog. Hosted charts bind
their owning application's logger and restore their own named preferences after
host attachment. An early child Load waits for the screen's display notification
and retries once its application logger and screen host are available. Existing
context-menu commands are preserved.
chart.LogOutput exposes the selector. chart.LogOutputBehavior.OutputSelector
can borrow a selector already owned by the containing screen. Set
CaptureEnabled = false when that selector receives raw observations from an
application-owned sampler; this keeps the same configuration command without
also logging chart history. Borrowed selectors retain their owner's lifetime.
Ordinary chart capture logs its current observations once when enabled, then
only appended or revised values. Graph observations use series and category/X
identity; telemetry uses the original UTC capture timestamp, so moving the
relative time axis does not repeat history. Entries are descriptive text with
invariant values, measurement names and units, for example
2026-10-22 01:02:03.456 Memory Activity — Memory Usage: 42.5 %.
The date/time is UTC without a timezone suffix or offset. Telemetry retains the
original capture time; ordinary numeric/native charts use the UTC publication
time. The chart title immediately follows that date/time. Already timestamped
chart entries bypass the selector's additional timestamp decorator, including
when its accepted timestamp option is enabled.
Related series at one captured time share one entry with every metric and unit; numeric/native series without capture times group by their shared observation identity. The timestamp and chart title appear once. A revised metric republishes the complete related sample, while unchanged history and redraws add no entries.
LogTitle supplies an explicit chart title; empty derives native chart titles,
the owning screen, a descriptive telemetry heading or its surrounding group.
Chart-owned log screens use that resolved name as Log Output - <NAME>.
TelemetryChart.LogSeriesName can name a measurement independently of a hidden
header. GraphChart.LogUnit can override units inferred from its Y-axis title.
Native adapter entries include every Y value and the category/X-axis position.
ChartLogSample supports optional CapturedAtUtc, Units and PositionLabel
metadata for custom providers without changing its four-argument constructor.
The selector's bounded queue performs output IO on its worker.
DroppedSamples reports rejected entries while the queue is full; retained
revisions can be retried on the next capture.
Charts retain the caller's current snapshot. The logger tracks only identities
in that snapshot, exposed by RetainedSampleCount; it does not accumulate older
windows. Clear and disposal release captured records and deduplication metadata.
The caller still chooses active chart history length. The shared output queue
is limited to 512 entries and 1,048,576 pending message characters. The log view
retains at most 262,144 pending characters and 1,048,576 displayed characters,
removing older text as those limits are reached.
For a native DataVisualization Chart, create a ChartLogOutputBehavior(chart)
in its owner's load lifecycle and call RestoreSettings() after its host is
attached. The adapter coalesces native invalidations and supports every native
series type and all of a point's Y values. Dispose the adapter when that surface
is removed; it also observes the chart's disposal. FlushAsync() awaits accepted
output while leaving capture enabled. DisposeAsync()/Completion observe its
owned output drain without blocking the UI; failures remain available through
LastError. Await completion before ending an
owning standalone message loop. These helpers belong to Framework WinForms and
add no logging dependencies to the chart engine assembly.
Scoped window outlines
WindowHighlightScope owns a hollow, nonactivating, click-through frame over caller-supplied physical desktop pixel bounds. Supply its color and physical-pixel thickness; update Bounds to follow a target, then dispose the scope to remove every overlay pixel. Create, update and dispose on the same STA UI thread. The frame uses a layered input-transparent window, leaving the target's device context and foreground activation untouched. The application owns target identity checks, timeout and selection policy. WindowsWindow.GetVisiblePhysicalBounds supplies verified geometry excluding invisible resize margins when DWM reports a visible frame; use it for an outline flush with the visible window. GetPhysicalBounds retains the outer GetWindowRect geometry including those margins. Both preserve the querying thread's DPI context. The frame draws inward from the supplied rectangle without adding an offset. No monitoring or timeout starts in the generic scope.
The frame's HWND is created and updated under a scoped per-monitor V2 awareness context. Native geometry and placement therefore use the same physical coordinate space even when a worker and UI thread have different awareness or monitors use different scales. The scope restores the thread's prior context after every operation; it does not change the application's overall DPI mode. DPI-change suggestions do not rescale an already supplied physical rectangle. Never multiply desktop coordinates by a global DPI ratio: monitor origins can be negative and scaling can differ between displays.
Keep this frame's managed Form.TopMost false. In .NET 10's Form implementation, SetVisibleCore explicitly focuses managed topmost forms even when ShowWithoutActivation is true; its TopMost setter also changes z-order without SWP_NOACTIVATE. WindowHighlightForm instead specifies native WS_EX_TOPMOST at creation alongside WS_EX_NOACTIVATE, retains ShowWithoutActivation, and rejects keyboard selection. Native tests verify the actual topmost style and zero activation/focus events/messages across first show, resize and reshow. Do not replace that native creation style with the managed property or restore a previously foreground window after an accidental activation.
Picking a desktop window
WindowPicker composes the existing Windows mouse/keyboard hooks and
WindowHighlightScope. Create it on a live UI dispatcher's thread, await its
one-use PickAsync(mainForm, cancellationToken), then dispose it on that owner.
The default worker query uses WindowsWindow.ReadAtPhysicalPointAsync and
verified physical frame bounds; no resource query or target control execution
runs in an input callback. Supplied hooks are owned; the dispatcher/main form
are borrowed. A caller may supply hooks and a detached worker query through the
constructor without replacing the component's presentation/lifetime logic.
Only the supplied main form hides. Owned modeless windows retain visibility through temporary owner detachment/restoration. Hover uses the existing red outline, which is disabled and input-transparent so native point lookup ignores it. The primary selecting DOWN/UP pair is consumed by the hook; ordinary hook consumers retain default pass-through. Escape/right-click/cancellation restores the frame and cancels worker reads. A consumed DOWN retains its matching UP before normal cancellation unhooks. A result contains the exact physical HWND owner and its captured process creation time; applications still verify resource identity when issuing subsequent commands.
VisualGrid.SetSearchTextAsync uses the existing search/first-page path.
LocateEntityAsync reads the current filtered/sorted source on a worker, moves
to the matching page and selects its accepted visible entity. Its predicate must
use detached data only. Superseding filters/publications reject stale selection;
the optional clearSearch is an explicit caller choice. It does not capture
resources or recursively search child panels.
Async modal dialogs (.NET 10)
Await modal operations from UI event handlers or methods returning Task:
private async void EditButton_Click(object sender, EventArgs args) {
var (accepted, userInput) = await EnterTextDialog.ShowAsync(this, "Edit name", "Name", "Current name");
if (accepted)
await DialogEx.ShowAsync(this, SystemIconType.Information, "Saved", userInput, "OK");
}
Use ShowAsync on DialogEx, ExceptionDialog, EnterTextDialog, ReviewTextDialog, PasswordDialog, LogonDialog, and VisualGridDialog; use GenericEditorForm.ShowFormAsync and QuestionDialogSession.AskQuestionAsync. Password input returns (DialogResult Result, string Password); text input returns (bool Accepted, string UserInput). These helpers dispose the dialogs they create after completion. When calling native Form.ShowDialogAsync on your own form, keep it in a using scope across the await.
DialogEx fits its message when shown on the owner's monitor. Short messages retain the designer's small size; longer confirmations grow the form and text viewport, widening when that reduces wrapping. Growth is bounded by the monitor working area and a 900 × 780 logical-pixel window limit, or a smaller caller-supplied MaximumSize. Text scrolls vertically once that limit is reached, with command buttons kept outside the scroll area. The existing 5,000-character text limit remains; use ReviewTextDialog for full reports.
Custom forms use .NET WinForms directly: using var dialog = new MyDialog(); var result = await dialog.ShowDialogAsync(this);. InvokeAsyncEx remains a UI dispatch convenience over native Control.InvokeAsync, propagating completion, exceptions, and cancellation; it does not implement a modal loop.
IApplicationDialog declares the native ShowDialogAsync overloads, implemented directly by the inherited Form methods. There is no legacy synchronous fallback. The caller retains ownership of an existing dialog. CRUD create, edit, and delete methods return Task; SourceGrid deletion uses DeleteSelectedRowsAsync. Custom DialogEx button behavior overrides OnProcessButtonAsync.
await wizard.Start(owner) on IWinFormsWizard<TModel> also awaits native Form.ShowDialogAsync, keeping its owner disabled until completion or cancellation and disposing the wizard dialog afterward.
Wizard screens receive their Wizard and Model before Initialize, including screens added with InjectScreen. Navigation calls Validate before OnNext; commit accepted input in OnNext when invalid input must not change the model. Set UpdateModelOnStateChanged = false for this pattern. The default OnPresent calls CopyModelToUI, so input and summary screens can refresh their controls each time they are shown.
Override a branching screen's Traits with WizardStepTraits.AssumeHasNext when OnNext injects its successor. The shared orchestrator displays Next immediately, even for a lone registered screen. If the callback does not supply a real successor, navigation reports an error and keeps the current screen rather than completing. Final screens retain WizardStepTraits.None.
WinForms closing and validation events still require cancellation and handled flags to be set before the first await. Synchronous grid queries and model construction can only schedule asynchronous error reporting; they cannot await a modal result. IWindowsFormsEditorService.ShowDialog, common file/folder/color dialogs, and the synchronous LiteMainForm.AskYN contract retain synchronous modal calls. AskYN uses a native message box; blocking ShowDialogAsync with .Result or .GetAwaiter().GetResult() on the UI thread would deadlock.
Run the STA regression tests with dotnet test tests/Sphere10.Framework.Windows.Forms.Tests/Sphere10.Framework.Windows.Forms.Tests.csproj on Windows. They exercise actual forms with a message loop and close their dialogs automatically.
Call await application.ExitAsync() to request shutdown and receive whether the main window actually closed. File > Exit and the close button delegate to that same application workflow. It owns one asynchronous native confirmation, the retained screens' close guards, the active screen's block and the selected block's CanExitAsync(application) permissions, and existing application-exit observers. Each distinct block is checked once. Repeated requests share the pending decision. A native FormClosing observer can still decline normal exit, and another request can retry. Window close continues to hide or minimize forms configured for those actions; explicit application exit closes the window. application.Exit() provides the synchronous counterpart, using the same pending decision and native message pumping on the UI thread. IsExiting identifies a pending request; HasExited identifies completed closure.
await application.ExitAsync(force: true) and application.Exit(force: true) skip confirmation and permission vetoes, including native FormClosing vetoes, while completing normal WinForms closure. Force also upgrades a pending normal request and dismisses its default confirmation dialog. Cancellation during confirmation dismisses that dialog and leaves the application available for another request. Once shutdown is committed, finalizers and resource cleanup finish even if a caller stops waiting. Exit dispatches onto the UI thread even when requested from a worker. Session-ending messages use forced graceful closure. A standalone main form retains its existing closing behavior and confirmation override. Once exit is approved, application and framework shutdown tasks complete before the main window closes; service-provider disposal follows after Application.Run returns.
Review text before saving
ReviewTextDialog shows the complete generated text in a read-only, scrollable preview, with Copy for the full text and Save for choosing a destination. It opens without selecting the preview. Use it for CSV, JSON and other text exports after generating the content with the framework's existing serializers/writers:
var savedPath = await ReviewTextDialog.ShowAsync(
this, "Review CSV Export", "Inspect the export before saving a copy.", csv,
"export.csv", "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*",
cancellationToken: cancellationToken, logger: application.Logger);
The helper returns the saved absolute path, or null when the user closes the review. Token cancellation disposes the helper-owned dialog, awaits native modal cleanup to restore the owner, then throws OperationCanceledException. It awaits native ShowDialogAsync(owner); the filename picker is the existing synchronous Windows common dialog. Construction and preview setup perform no file IO and require no application services, including on the designer surface.
For an existing dialog instance, configure PreviewText, Instructions, DefaultFileName, Filter, OutputEncoding and optional borrowed Logger on the creating UI thread. SaveAsync(path, cancellationToken) saves without opening a picker. The default encoding is UTF-8 without a BOM. A complete temporary copy in the destination directory is written before replacing the destination; save failure or cancellation preserves its original content and cleans up the dialog's temporary copy. Saving prevents simultaneous saves and normal closure. Disposing the dialog cancels an outstanding save. The dialog reports save failures through Logger, leaving its options and disposal with the caller.
Byte and hexadecimal editing
HexEditorControl is a designer-editable hex editor over any seekable Stream. Open content with OpenFile(path, readOnly), OpenStream(stream, ownsStream) or SetDocument(document, ownsDocument); Document assignment borrows. The control derives from ApplicationControl, so it also works as a hosted screen component. Nothing beyond the visible window is loaded: HexEditorDocument reads through a StreamByteCache (64 blocks of 4 KiB by default, configurable per document) and keeps pending edits in a piece table until Save(). Overwrites (WriteByte, Overwrite) are written in place as coalesced runs; insertions and deletions (Insert, Delete) change Length, and saving them resizes the stream and rewrites it from the first pending change, staging the tail in memory up to MaxInMemoryRewriteBytes (64 MiB) and in a temporary file beyond that. The toolbar's Save, Ctrl+S and the form's menu call SaveAsync(cancellationToken), which writes on a worker thread: while IsSaving is true the document refuses edits, the status bar shows Saving..., and viewing, scrolling and searching continue, since the save holds the document's lock one 64 KiB step at a time and reads between steps see the pending content. A stream that cannot be resized (a fixed MemoryStream over an array) rejects such a save and keeps the edits pending. Revert() discards everything. A non-writable stream, or ReadOnly = true, makes the document read-only. BaseAddress on the control or viewport shows a memory region's virtual address or a file slice's offset in the address column, status bar and Go To while every API offset stays document-relative.
The view shows an offset column (AddressDigits on the viewport: automatic, at least eight hex digits), hex bytes grouped in eights with 1 to 256 per row (BytesPerRow, 16 by default), and a decoded text pane. The toolbar's Bytes per row list offers 8, 16, 24, 32, 48 and 64, dragging the line between the hex pane and the text pane chooses any other number, and the form's View menu offers 8, 16 and 32. The caret is synchronized across both panes; Tab switches the pane with keyboard input. Click or drag to select, Shift+click or Shift+arrows to extend, Ctrl+A to select all; arrows, Home/End, PageUp/PageDown and Ctrl+Home/End navigate; the mouse wheel scrolls. Typing hex digits overwrites nibbles; typing in the text pane overwrites bytes with character codes. Insert mode (Insert key, toolbar toggle or InsertMode) types and pastes new bytes at the caret instead, including at the end; Delete removes the selection or caret byte, and Backspace removes the byte before the caret in insert mode. Modified bytes stay highlighted until saved. The toolbar, the control's shortcuts and the form's menus expose Save (Ctrl+S), Revert, Go To (Ctrl+G, hexadecimal or decimal), Find (Ctrl+F, hexadecimal pairs or UTF-8 text, forward or backward), Find Next/Previous (F3, Shift+F3), Copy Hex and Copy Text (Ctrl+C copies in the active pane's format, Ctrl+Shift+C the other; Viewport.MaxCopyBytes bounds the selection), Paste (Ctrl+V, hexadecimal pairs in the hex pane or UTF-8 text in the text pane, replacing a selection) and Select All. FindAsync(search, backward) runs HexEditorSearch on a worker thread with a sliding window that never loads the stream and bypasses the viewport cache; the match is selected and reported in the status bar. The status bar shows the caret offset, selection range and length, document length, pending modification count and the Read-only/Overwrite/Insert/Saving mode. The data inspector lists Int8..UInt64, Single, Double, ASCII and UTF-8 at the caret with a big-endian toggle (BigEndian); ShowDataInspector, ShowToolBar and ShowStatusBar hide the panels.
HexEditorViewport is the non-visual view model (visible row window, caret, half-open selection, active pane, typing) that HexEditorView paints and that tests drive without a message loop; HexEditorDataInspector produces HexEditorInspection values. HexEditorView is double-buffered, DPI-aware and uses a monospace font with ordinary WinForms colors (OffsetForeColor, ModifiedForeColor, SelectionBackColor, InactiveSelectionBackColor and friends default to SystemColors), so it follows light or dark system colors; the library has no separate theming facility. StateChanged publishes document edits, ViewChanged reports caret, selection and scroll changes, and DocumentChanged reports a replaced or closed document. All control access belongs on the creating UI thread.
HexEditorForm hosts the control with File, Edit and View menus, asks before discarding pending edits, and shows the document title with a * while modified. await HexEditorForm.ShowAsync(owner, stream, title, ownsStream, cancellationToken) and ShowFileAsync(owner, path, readOnly, cancellationToken) show it modally; token cancellation closes the window and throws. HexEditorGoToDialog and HexEditorFindDialog are the designer-editable prompts the control uses.
Application lifecycle and splash
Declare WithName(...) before calling AddInitializer or AddFinalizer. Both type and factory overloads throw InvalidOperationException immediately when the plugin has no name.
IApplication exposes Initialize() / InitializeAsync(...), Finalize() / FinalizeAsync(...), Exit(...) / ExitAsync(...), Logger, Disposables, lifecycle events and Progress. Initializing an application runs its tasks once; concurrent calls await the same operation. Merely building a plugin, resolving the application or reading its properties does not run its tasks. Finalization waits for attempted initialization, runs shutdown tasks once and releases application-owned resources; disposing the application also completes that cleanup. Finalization alone does not close the main window: request closure through ExitAsync. Task collections remain protected implementation details of ApplicationBase.
ApplicationPluginBuilder inherits AddInitializer<T>() and AddFinalizer<T>() from the shared plugin builder. Their factory overloads accept Func<IServiceProvider, T>. These helpers register transient lifecycle tasks keyed by the built plugin's Name; duplicate names are rejected at load, and custom plugin names must remain stable. Different plugins can register the same task type without sharing its instance. The application resolves and caches tasks for its successful LoadedPlugins through its own provider. Host registrations using services.AddInitializer<T>(typeof(IApplication)) and services.AddFinalizer<T>(typeof(IApplication)) remain supported for application-owned tasks. The combined inventory starts with host-owned registrations in registration order, followed by plugins in LoadedPlugins order and each plugin's tasks in declaration order. Initializer priorities apply across this inventory within the existing sequential and parallelizable phases; finalizers execute in combined inventory order. Existing unkeyed framework tasks retain their process startup and shutdown behavior. Use AddServices for other plugin dependencies.
Derive synchronous tasks from SyncApplicationInitializerBase or SyncApplicationFinalizerBase and override only their synchronous method; the base supplies the worker-task async bridge. Derive asynchronous tasks from AsyncApplicationInitializerBase or AsyncApplicationFinalizerBase and override only their asynchronous method; the base supplies the synchronous bridge. The common ApplicationInitializerBase and ApplicationFinalizerBase leave both methods abstract. Tasks requiring native UI affinity can implement both contracts there and dispatch to their owning UI thread.
Application derives from AsyncApplicationBase: its asynchronous readiness hook installs blocks on the owning UI thread before awaiting application tasks. Worker lifecycle requests start through InvokeAsyncEx; synchronous native lifecycle and disposal calls pump UI messages while waiting for the same asynchronous operation. This preserves UI continuations without sending block registration to a worker. Pending lifecycle work still follows the shared coalescing, cancellation and disposal guards.
StartWinFormsApplication starts the framework with the native message loop running. Module initialization finishes before it constructs the application root; global initializers then run with that exact IApplication.Logger, including an override of the registered process logger. Constructing the root does not install blocks or create screens. Framework.Initialized still runs before block installation and application.InitializeAsync(), which finish before showing the main window. A vetoed block installation can retry without running application tasks. Approved exit awaits application finalization and then runs framework finalizers while the main window remains open with interaction disabled. The window closes after these tasks; the runner waits for the root's exit result before ending the message loop and disposing the service provider. Cleanup still proceeds when a finalizer fails. Disposables holds resources owned by the application, independently of the borrowed form and screen host.
Enable the startup and shutdown splash with .UseSplashScreen() or .UseSplashScreen(image) on the BuildWinFormsApplication() chain. It retains its framework events and global information logger, subscribes to process task progress even with a custom application logger, and subscribes to application lifecycle and progress before initialization. After exit confirmation and all closing permissions succeed, a fresh splash appears immediately at full opacity and displays application and framework shutdown tasks while the main window remains behind it. Closing the main window is the last step after those tasks. The splash then fades out during resource cleanup. A failed initialization reuses its still-visible splash for cleanup. Updates from worker tasks queue onto the UI thread. Startup retains its fade-in; shutdown does not fade in. The overload .UseSplashScreen(image, configure) applies the same Action<SplashScreen> to each startup and shutdown instance. ProgressOverImage places the real lifecycle text over the artwork; ProgressBounds, ProgressBackColor, ProgressTitleColor and ProgressMessageColor customize that area. An optional ProgressTextFormatter can turn task identifiers into display captions while preserving meaningful messages and errors. Existing overloads retain the separate default footer. Supplied artwork remains caller-owned; the splash disposes its resized copy. Application tasks touching native controls must run on the UI thread; reserve parallelizable tasks for work that does not access controls directly.
The root's Logger is the framework Sphere10.Framework.ILogger, resolved from its provider with SystemLog.Logger as the fallback. Lifecycle tasks can inject IApplication; hosted screens can reach the same logger through Block.Parent.Logger. Add only application-owned resources to application.Disposables; services, the form and the host keep their existing disposal owners. The adapter does not call plugin Unload() during shutdown.
Application screen hosting
Use application and screen lifetimes
to assign refresh work, subscriptions and capture leases. Screen overrides own
screen work; initializers/finalizers own shared application services. In
particular, OnHide is a preflight guard, not a destruction callback.
IApplicationScreenHost in Sphere10.Framework.Application.UI owns available and registered blocks, active navigation, the active screen, UI services, view mode, unsaved changes and lifecycle guards. ISingleApplicationScreenHost adds operations on the current screen; IMultiApplicationScreenHost adds retained/open collections, ordering and instance operations. The native host implements both interfaces and can switch modes through the guarded ScreenMode setter or TrySetScreenModeAsync. IUserInterfaceServices owns dialogs, status, UI dispatch and command execution. Read them from application.ScreenHost.UserInterfaceServices. The application exposes live Blocks, successful startup LoadedPlugins, its host and application commands; ScreenHost.ActiveBlock owns the selected block.
AddMainForm<TForm>() registers shared, typed and native hosting interfaces against the existing host of a MainForm; it does not create another workspace. UI services resolve the form. Inject the common host for navigation and lifecycle operations:
using System.Threading.Tasks;
using Sphere10.Framework.Application.UI;
using SharedUI = global::Sphere10.Framework.Application.UI;
public class WorkspaceNavigation {
private readonly SharedUI.IApplicationScreenHost _host;
public WorkspaceNavigation(SharedUI.IApplicationScreenHost host) => _host = host;
public Task<bool> ExecuteAsync(SharedUI.IApplicationMenuItem item) =>
_host.UserInterfaceServices.ExecuteMenuItemAsync(item);
public Task<SharedUI.IApplicationScreen> OpenEditorAsync(SharedUI.IApplicationBlock block, SharedUI.ApplicationScreenDefinition definition) =>
_host.OpenScreenAsync(block, definition);
public Task<bool> CloseActiveEditorAsync() => _host.ActiveScreen == null
? Task.FromResult(true)
: _host.CloseScreenAsync(_host.ActiveScreen);
}
The native host exposes actual ApplicationScreen instances through every hosting interface. Screens includes retained singleton controls even when hidden; OpenScreens follows open order, including detached windows. Control identity remains stable across hide, show, docking and title changes. SelectBlockAsync browses a block without replacing the active editor; ActivateBlockAsync opens its default screen. Both navigation and hosting changes raise Changed. Showing a retained screen again selects its owner for application navigation.
For a configured screen that should start in a modeless detached window, use await application.ScreenHost.ShowScreenUndockedAsync(screen) through the shared IApplicationScreenHost. The native host also retains ShowScreenUndocked(screen) for synchronous native callers. In MultiView, a new normal nonpermanent instance opens centered over its main frame without inserting or selecting a main-frame tab, changing the active block, or asking the current main screen to hide. The host retains the exact instance; it remains available in Screens and can be docked through the ordinary guarded controls. Showing an existing detached instance activates its window. Showing an existing docked instance this way uses the usual undocking checks. A false result leaves an unretained supplied instance with its caller. Ordinary ShowScreenAsync(screen) keeps the normal docked launch behavior.
The generic IApplicationScreenHost<TBlock, TScreen> provides typed blocks, screens and lifecycle operations once for every platform. IApplicationScreenHost adds native docking and existing synchronous presentation APIs. A reference to a screen identifies the same object through neutral, generic and native interfaces. Blocks also use reference identity; distinct native block definitions can have matching names.
The native adapter composes the common logical host and performs native presentation on the UI thread. Its binding dictionary contains native presentation state, including tabs, detached windows and tab image keys. A screen exposes its public native Host and owning Block through both native and shared contracts; ApplicationBlock remains an alias of Block. These references are available during activation and destruction hooks, remain attached while a singleton is hidden or a window is undocked, and clear when the instance leaves the host. A ApplicationScreen can also access the owning shared host through protected ApplicationScreenHost and close itself with await ApplicationScreenHost.CloseScreenAsync(this).
OpenScreenAsync(block, definition) accepts a registered block and an exact definition reference from its ScreenDefinitions. Blocks own immutable definitions independently of menus, so a screen can open without a navigation item. A menu item references ScreenDefinition, and the block's DefaultScreenDefinition references the desired startup definition. Use RegisterBlockAsync and UnregisterBlockAsync for application membership; guarded removal closes its native controls and updates the same host registry.
AddScreen<TScreen>(configure, out registration) returns an opaque reference to
that exact block registration. Pass it to AddShowScreenItem(registration) or
WithDefaultScreen(registration); the ordinary overload needs no unused out.
Register existing definitions with AddScreen(definition). A menu item configured
with WithScreen<TScreen>() is only a pending reference and does not register a
screen. Missing and foreign exact references fail validation. Type-based menu
references choose the first match, while type-based defaults and programmatic
lookup require one unambiguous registration. A menu-free registration remains
available to OpenScreenAsync(block, definition) and has no invented activator.
Give same-type registrations distinct WithStableKey values when their identity
must survive a restart. Changing captions, menu order or adding an earlier menu
item does not redefine a registration's persistent identity.
Menu items expose their declaring menu through Parent, and menus expose their block through Parent. Adding and removing items and menus through their containers maintains these references. A screen definition's Activators array is a snapshot of the commands attached to menus that reference it; replacing a command's definition or removing the command updates that reverse membership. Application-level menus have no block parent. Rendering merged menus preserves each command's original parent. Screen commands, including toolbar commands, require their declaring menu's block through item.Parent.Parent. Ordinary application actions can run without a block or menu parent.
A registered block's Parent references the running application. That link follows live host membership and clears when the block is removed or the application adapter is disposed. Source records the plugin that successfully contributed the captured block; standalone blocks have no source plugin. Removing and registering a contributed block again preserves its source, independently of its current application membership. Native and shared interfaces expose the same references.
Execute the actual menu item supplied by the registered block, and pass the actual block, definition or screen to host operations. Ownership comes from these references; command dispatch does not search blocks for matching captions or IDs. The typed WinForms contracts specialize Parent, Source, Host and Block, with inline bridges to the shared interfaces under #region Base Interface Bridges.
Native screen construction
Native screen tabs prefer ApplicationScreen.ScreenImage, including for
screens launched directly without a menu activator. Set this designer-editable,
borrowed image before the screen is first hosted and keep it alive while hosted;
neither screen nor host disposes the supplied image. If it is null, the host uses
a registered screen activator image, including another definition for the same
screen type. The host owns its image-list entry, keeps each tab's image key across
docking and releases that entry when its screen is removed. Shared definitions
remain platform-neutral.
A registration can supply WithActivator(context => ...) to construct its actual
control on the owning UI thread. The context exposes the executing services,
host, block, owner and definition. That exact registration's factory is
authoritative; a result already owned by another host, block or registration is
rejected. A manually constructed standalone host may have no service provider.
The default ApplicationScreenHost.CreateScreen selects compatible
(block, owner) or (block) constructors, then a parameterless constructor.
It does not automatically resolve arbitrary DI constructors. When a screen
needs application-registered dependencies, adapt that construction boundary or
override the host factory; verify the real menu activation path uses the intended
service instances. Do not assume a manually constructed DI screen proves hosted
activation uses DI.
Keep explicit dependency constructors for standalone use and a parameterless
designer constructor for hosted construction. Initialize the static layout, then
return in design mode before resolving providers or binding services. Runtime
screens can use the application's configured provider or an overridden host
factory for shared collectors. Hosted screens use Block.Parent.Logger for
application diagnostics. Reusable typed Windows resource APIs live in
Sphere10.Framework.Windows,
independently of an application checkout. Collectors, sampling policy and display
models live in the application and compose these APIs.
⚡ 10-Second Example
using Sphere10.Framework.Windows.Forms;
// Create a database connection panel that adapts to selected DBMS
var connectionPanel = new DatabaseConnectionPanel();
connectionPanel.SelectedDBMSType = DBMSType.SQLServer;
// Get connection string and DAC from the panel
string connectionString = connectionPanel.ConnectionString;
IDAC dac = connectionPanel.GetDAC();
🏗️ Core Concepts
Database Connection Controls: DatabaseConnectionPanel dynamically loads appropriate UI based on selected database type (SQLite, SQL Server, Firebird).
Custom Controls: Enhanced controls like PathSelectorControl, ProgressBarEx, PropertyGridEx, RadioGroupBox, and validation indicators.
PropertyGridEx.AutoSizeLabelColumn opts into measuring the visible property
captions rather than using the native default label/value split. Labels adapt to
the current font, DPI, object and viewport, bounded by MaximumLabelColumnWidth
(320 logical pixels) and MaximumLabelColumnRatio (0.4). Values receive the
remaining width. A native splitter drag or keyboard adjustment takes precedence
until ResetLabelColumnWidth() is called. The same control, selected object,
property selection and native view remain in place.
The optional splitter adapter targets .NET 10's internal PropertyGridView
LabelWidth and MoveSplitterTo members. Native minimum/maximum splitter limits
still apply; for example, very wide views reserve at least roughly one ninth for
labels. If a future runtime removes those members, automatic sizing disables
itself and the normal property grid remains available. Readonly is retained as
a legacy marker; use property descriptor ReadOnly metadata to govern editing.
It no longer clears native selection, an unsupported operation on .NET 10.
Data Binding: Enhanced data binding with validation and change notification.
Wizard Framework: Multi-step wizard UI pattern implementation.
Source Grid: Advanced data grid component for tabular data display.
🔧 Core Components
VisualGrid
See grids and screen hosts on both platforms for the Blazor equivalents, shared contracts and platform differences.
IHierarchicalDataSource enables recursive child grids automatically; CreateDetail
customizes their presentation and supports ordinary owned panels.
HeaderVisible, ColumnHeadersVisible and FooterVisible are independent. See
row detail surfaces
for worker preparation, identity, ownership, limits and the WinForms tester demos.
The search editor shows a centered magnifier when empty and a red cross while filter text is present. Click the cross to clear the text and restore the grid's unfiltered query through its existing search workflow.
Set GridTitle to a meaningful content name in the designer or constructor.
It updates the caption synchronously on the creating UI thread without requiring
an existing window. When a live handle requires cross-thread dispatch, the
setter queues the caption update and tolerates native-handle teardown.
A nonempty title keeps the header visible when the grid is disabled or the source
offers no create, delete or search controls. Changing the title updates header
visibility without explicitly reading or rebinding the source. Normal Auto paging
may refresh if that layout change alters the viewport's page capacity. An untitled
header collapses only when none of those controls is supported.
Use VisualGridCellDisplayType.Image with an Image-typed column and its value getter
for an image cell, such as an executable icon. These cells are read-only and do
not instantiate the text editor. The grid borrows the supplied image; its data
source/screen retains ownership and must keep it alive through presentation.
Extract/load expensive images on a worker and use an owned bounded cache rather
than querying the filesystem during cell painting. The reusable Windows
FileIconCache
returns borrowed images; keep its lifetime longer than the cells displaying them.
Image columns use ImageAlignment from Core's Sphere10.Framework.ResizeAlignment,
defaulting to CenterCenter at the original image size. Set ImageResizeMethod
to ResizeMethod.AspectFit, AspectFitPadded, AspectFill or Stretch
to scale within the cell content area. Null uses native-size placement with
SourceGrid's existing clamping when the cell is smaller than the image. Fit leaves the
remaining cell background visible; alignment also controls padded placement and
fill cropping. Ordinary and worker-prepared cells share one view per image column,
retain prepared slots on refresh and keep source image ownership with the caller.
Explicit scaling uses the existing Image.Resize API and disposes its temporary
bitmap after painting; it does not create an owned image per cell.
Natural header sizing reserves the actual sort glyph extent before the first
sort, so a later ascending or descending indicator cannot cover the measured
caption. Sorting keeps the established widths; explicit user widths still take
precedence. SourceGrid's SortIndicator.ReserveSpaceWhenUnsorted defaults to true.
Every column is sized by dragging a header boundary. The line is grabbed from either side, within four logical pixels scaled to the grid's DPI: inside a header's right edge the drag resizes that column, and inside the next header's left edge it resizes the column before it. Releasing the mouse after a resize does not also sort that column. A width the user drags is kept while a live refresh is reading and after the refresh completes.
VisualGrid hides the create and delete buttons when their respective capabilities are unavailable. Delete is also hidden unless a visible row is selected. Toolbar and paging controls size to their contents, including scaled fonts and DPI.
Set AllowCellEditing = true to edit columns with CanEditCell = true and a SetPropertyValue binding; CanUpdate must also be enabled. Changing the editing setting updates existing cells immediately. LeftClickToDeselect defaults to true and toggles a row on successive single clicks, including Ctrl-clicks. When both settings are enabled, double-click an editable cell or press F2 to edit while keeping its row selected; checkbox values also change only through that explicit edit gesture. Set LeftClickToDeselect = false to retain selection on repeated clicks and enable single-click editing. These selection modes also support SelectOnMouseUp.
Read-only text cells retain type conversion through SourceGrid's nonvisual
EditorBase, without constructing a WinForms editor control or attaching a
write-through controller for every displayed value. Enabling effective editing
later creates the normal editor for eligible columns without rereading the source;
revoking it cancels drafts and detaches persistence callbacks. Empty cells require
no editor. This keeps complete read-only inventories lighter during refresh.
For frequently refreshed read-only tables, AutoSizeRowsOnRefresh = false can
retain measured heights of ordinary single-line text/image rows. Initial binding,
new rows, changed image height, multiline/wrapped content and custom/editable cells
still measure. Source, bindings, column widths, fonts and DPI changes invalidate
the retained geometry. The default is true, preserving normal per-refresh sizing.
PrepareReadOnlyCellsInBackground = true opts a worker-safe read-only Text/Image
table into background source reads, result enumeration, CellHasValue/value
delegates and display conversion. The source, row objects, delegates, converters
and borrowed images must support that execution context; the default remains
false for UI-affine consumers. Keep column configuration stable during a refresh,
or replace GridBindings to supersede an in-flight result. Editable columns and
other display types keep their existing owner-thread path. Prepared value records
contain the original typed values and cached display strings, so sizing and
painting do not reevaluate model delegates or converters. Only plain compatible
prepared cells reuse their complete native cell/model/editor graph, replacing
snapshot values without edit callbacks. Row and reverse-selection lookups are
also prepared on the worker. First/new row slots create their detached native
cell graphs there too, before attachment on the owner thread. Native controls, editing, selection and
layout remain on the owner thread. Superseded/disposed preparations are discarded
before publishing a page. Targeted row refresh follows the same preparation
contract. Image ownership stays with the caller, including while preparation is
in flight. An explicit programmatic cell-value change outside the data source
uses the normal converter until the next prepared refresh.
Prepared grids also divide native first sizing and later row remeasurement into short owner-thread slices. A WinForms timer admits each subsequent slice, giving pending input and painting a real message-loop opportunity. Each slice completes its redraw/layout scopes before yielding; graphics and editor controls stay on the owner thread. SourceGrid's measurement order, intrinsic widths/heights, visibility and auto-size flags remain in use. Query, permission, disposal and font/DPI/geometry changes are checked between slices, and explicit column widths chosen during sizing survive completion. The initial loading surface stays in place until the accepted page has finished sizing. Other grids retain their existing synchronous sizing behavior.
When a resize changes native sizing geometry during a prepared binding, sizing retries over the already committed cells. It does not reread, reconvert or rebind the same snapshot. Actual query or binding changes still supersede the result.
GridTitleAlignment uses System.Drawing.ContentAlignment and defaults to
MiddleCenter for compatibility; choose MiddleLeft for a left-aligned table title.
The header collapses hidden Create/Delete button slots, so a read-only title
starts at the normal header inset rather than reserving space for unavailable actions.
The footer keeps Total on the left and a compact grid-icon menu button, Page Size and navigator aligned on the right. The menu lists Single, Auto and Manual, with a checkmark on the selected mode; its tooltip names that mode. Narrow hosts wrap complete groups without clipping their controls. PageMode retains the existing VisualGridPageMode API:
| Mode | Behavior |
|---|---|
Manual (Paged) |
Manual Page Size label/editor and page navigator. Sizes range from 1 to 9999, in steps of one. |
Auto (Auto) |
Page navigator remains available; the manual label/editor are hidden. The actual ordered row heights, header and scrollbar-adjusted viewport determine how many complete rows fit, with a minimum of one. Resize, font and DPI changes recalculate capacity. Taller individual rows do not inflate the budget for every ordinary row. |
Single (Single) |
All matching rows in one vertically scrollable page. The manual size and page navigator are hidden; the source receives page zero and int.MaxValue page length. Search and sorting still apply. |
Switching modes starts at page zero and retains the remembered manual size for returning to Manual. AutoPageSize remains a compatibility alias: true selects Auto, false selects Manual. The Paged enum value and stored preferences remain unchanged. Sources without CanPage retain their existing complete-result behavior and hide the paging footer. Navigation and sorting remain active for Manual and Auto; Single always uses page zero. Saving their configuration is an explicit screen-owned action.
Auto paging settles both larger and smaller capacities after native measurement. Measured viewport/header/row dimensions already use the window's device pixels; only an unmeasured fallback is DPI-scaled. A bounded fitting result prevents repeated probes when a taller next row cannot fit. Short final pages retain their remaining rows without an attempt to fill from nonexistent data.
For rapid live updates, set SuppressLoadingIndicator = true. Refresh begins immediately, without the normal stampede delay, loading animation or temporary grid disabling. It retains the logical busy state, joins an active refresh task and discards superseded query results. The default remains false for ordinary data loading. The WinForms tester's CRUD screen exposes the option for its grid and dropdown.
An owner whose own work takes a while shows its own message with ShowLoading(title, subtitle, image, disableInput) and removes it with HideLoading(); LoadingVisible reports it. This is separate from the automatic indicator of a data source read and reads no data:
grid.ShowLoading("Searching Modules…", "Reading The Modules Of Every Process");
try {
rows = await SearchAsync(query, cancellationToken);
} finally {
grid.HideLoading();
}
The message shows an animated circle, or a copy of the supplied picture, above a bold title and an optional subtitle. By default it covers the grid so its rows cannot be used; disableInput: false shows a centred card and leaves the rows usable. A repeated call replaces the message, the grid's Enabled state is never changed, and HideLoading leaves the automatic indicator of a read in progress alone. Call both on the grid's UI thread.
While a suppressed refresh awaits data, selection, deselection, paging and row context menus continue against the last committed page. A right click first selects its actual row. Internal native publication gates selection callbacks until the replacement page and its lookups are consistent; the newest user selection is then retained where possible. This does not permit inline editing or CRUD mutations during a refresh, and replacing the source or columns blocks interaction with the superseded view. Ordinary loading and initial binding keep their normal input gate.
When the selected logical entity stays on the same physical row, accepted refreshes retain SourceGrid's selection object, focus and selected region. They do not clear/reselect that row just to publish replacement counter values. If row membership changes, selection is reconciled against the accepted entity-to-row lookup. This preserves the painted highlight without disabling native mouse input or suppressing HWND redraw.
At runtime a newly created grid shows its loading surface immediately. First binding and later ordinary refreshes use the same full-grid overlay, with painted spokes scaled to the current viewport and resized with its host. Its search, CRUD buttons, table and footer remain covered until the first completed RefreshGrid() after SetDataSource(...); a slow capability read or initial collection cannot expose designer placeholders. Nested loading operations retain the overlay until the last operation completes. SuppressLoadingIndicator suppresses later routine updates, while the first binding retains this loading surface. The Visual Studio designer still displays the editable normal layout.
After a selected-row operation, await RefreshEntityAsync(entity) or RefreshSelectedEntityAsync() to reread only that visible row through the source's RefreshRangeAsync. The source can replace the array entry with a fresh instance, or null when it disappeared. The grid retains page/sort settings, column widths and unaffected rows, and transfers selection to the replacement. A false result means the row is no longer visible or a source/query change superseded it. This requires a source that implements entity refresh; the standard read-only SnapshotDataSource<T> deliberately does not. A caller-owned snapshot source can supply that behavior without adding application collection policy to the grid. Targeted and full-page refreshes share scoped asynchronous admission.
Click a sortable column header to cycle Ascending → Descending → None, then ascending again. None clears the header arrow and requests the source's natural order with SortDirection.None; changing to another column starts ascending. Sorting preserves the current page and established column widths. An explicitly saved cleared sort persists across sessions. SnapshotDataSource<T> honors explicit None even when a default sort is configured; the initial null column with Ascending still requests that configured default.
grid.TotalRecords exposes the last accepted query's filtered total across all
pages. DataBindingComplete runs on the grid's owning thread after the current
query is bound, including zero matches; superseded reads do not emit it. Use
these members for external summaries without querying or enumerating the source
again. VisibleEntities remains the displayed page only.
grid.CaptureVisibleEntities() returns the displayed page, in display order, as
an Array of the bound item type. It queries nothing, so it is exactly what the
user sees and a concurrent refresh cannot invalidate it. Exporters use it for
"export what is shown"; a grid in Single page mode displays, and so returns,
every matching row.
await grid.ReadFilteredEntitiesAsync(cancellationToken) captures the current
source, search and sort on the owning UI thread, then reads and materializes all
matching rows on a worker, across pages. It does not rebind, disable the grid,
show an indicator or change page/selection. The returned Array retains the
source's declared item type, including an empty result, so exporters can retain
typed CSV headers. It queries the bound source rather than calling a separate
collector; snapshot sources therefore reuse their published inventory.
With the grid's PublicationIdentity configured, export validates that stamp
at admission and completion and throws InvalidOperationException for a stale
publication. Committed rows remain interactive, and source membership is never
rolled back or replaced by this check.
Columns take their natural widths from the first nonempty result for a binding set, then keep those widths across paging, searching and refresh. Longer values on a later page do not resize the table. Explicit user resizing takes precedence and survives subsequent reads. Columns marked ExpandsToFit share spare viewport width when the viewport changes; an explicitly resized column keeps its chosen width. Assigning a new binding set starts a fresh natural-width calculation. Right mouse-down selects the clicked data row before a context menu opens in either left-click selection mode, without starting an editor or toggling checkbox values; headers and empty space do not open an entity menu.
ColumnLayoutSource optionally borrows another live grid's column definitions,
display order, visibility and resolved widths while leaving queries, paging and
selection local. The source remains the sole owner of column preferences.
For recursive tables, set ShareDetailColumns = true and omit a
separate child layout. Shared child hosts retain the parent's native column
origin and horizontal scroll; hierarchy indentation is inside column content.
DetailIndentColumnKey selects the stable column key for that gutter, useful when a
narrow icon column precedes the name. Children keep their own vertical scroll.
Nested child tables need a control per expanded row, so their expansion is bounded
(MaximumExpandedDetails, at most 128). To show a whole tree, bind a source that
serves an outline instead, such as a KeyedHierarchyDataSource<T> with
Presentation = HierarchyPresentation.Outline. Set Outline to it, set
DetailsEnabled = false, and choose OutlineColumnKey: that column indents each
row by its depth and draws an expander beside a row with rows beneath it. A click on
the expander, or Right and Left on the selected row, shows or hides them.
ExpandAllAsync, CollapseAllAsync and SetOutlineExpandedAsync change the
source's expansion and read it again.
See native row details
for ownership, settings and complete examples.
The owning screen keeps one VisualGridSettings value per logical grid inside
its actual ScreenSettings object. Screen Options owns the configuration editor,
and the screen's existing settings provider owns persistence. VisualGrid has no
settings button, local settings dialog or independent settings record. An ordinary
standalone consumer may retain a settings value through its own lifecycle.
See per-user UI settings.
Declare complete column keys and readable titles in the screen's value-only
defaults so Options lists the columns before the screen opens. Reconcile older or
empty saved column arrays against those declarations, preserving accepted widths
and stretch choices by key. Do not depend on a grid-local dialog to discover the
column schema. Arrange the screen's Columns collection to choose the displayed
column order. Width and stretch choices remain associated with each stable key
when columns move.
Bind VisualGrid.Preferences to the appropriate screen-owned value, using a
distinct named role for each grid. CaptureGridPreferences() returns detached
values; ApplyGridPreferences(values) applies accepted values without saving or
discarding a live cell draft. Query changes defer until the editor ends.
PreferencesChanged reports runtime page/sort choices and completed header
drags. Those operations remain transient: they do not overwrite the accepted
screen settings section or become persistent merely because the screen closes
or the application finalizes.
A screen can drop a VisualGridConfigurationContextMenu component into its
designer and assign it to the grid's generic HeaderContextMenuStrip property.
For code-based attachment after InitializeComponent():
_messages.HeaderContextMenuStrip = new VisualGridConfigurationContextMenu(components);
await BindGridPreferencesAsync(_messages, nameof(MailScreenSettings.Messages));
Right-click a column header for Save configuration and Restore defaults.
Save captures only the clicked grid's current configuration into its existing
screen settings section and persists the actual root through its provider.
Restore applies that grid's complete defaults from the screen settings class to
the current view. DefaultsRestorePolicy defaults to
VisualGridDefaultsRestorePolicy.RestoreOnly; RestoreAndSave also persists
those restored values through the same screen owner.
Those defaults include columns/order, page mode/manual size and sorting. The
same menu can serve multiple bound grids; its native SourceControl identifies
the clicked grid, and it resolves the owner on demand. An ordinary custom
ContextMenuStrip can be assigned instead. Unbound grids have no screen
configuration to save. Screen Options remains the column configuration editor
and saves accepted edits through its Apply/OK actions.
The compact footer selector continues to offer Single, Auto and Manual
(Paged in the API), alongside the normal manual page-size control and navigator
where appropriate. Search, sorting and paging remain ordinary grid operations.
Automatic fitted capacity never overwrites the remembered manual size, and
viewport resizing or source refresh does not write settings.
Manual widths use IVisualGridColumn.PreferenceKey, normally the property or
source sort name. Supply an explicit stable key for computed columns and keep
keys unique. Captions and column positions can change without losing overrides.
Widths use logical pixels at 96 DPI, remain stable across rebinds and DPI changes,
and leave untouched natural/stretch columns unspecified. The header's Restore
defaults command uses the menu's configured policy, defaulting to a temporary
restore; Screen Options Reset remains provisional until Apply/OK.
Snapshot collection and binding
Configure an existing ranged IDataSource<T> directly on the grid with
ConfigureDataSource(source, resolvePublishedEntity, visibleSelectionIdentity).
Configuration is synchronous and performs no reads. Await
RefreshDataSourceAsync(cancellationToken) for the first binding and subsequent
source publications. The grid binds once and serializes publication without
materializing the entire source into another snapshot. Search, sort, paging and
total count stay with the source. The optional selected-entity resolver maps a
captured model to the source's current replacement. Configure and refresh on the
grid's owning dispatcher; the source remains responsible for worker execution.
Set SuppressLoadingIndicator for an unobtrusive live refresh that keeps the
committed page available while the next read is pending. RefreshGrid() remains
the ordinary page refresh; SetDataSource remains the awaited assignment API.
The snapshot controller below uses the same grid-owned binding mechanism.
Where commands apply only to selected visible rows, explicitly configure
VisibleSelectionIdentity with a stable key and update commands from
SelectionReconciled. Accepted bindings then select the current matching row or
clear a selection excluded from the page/filter. These members belong to the
grid. The identity defaults to null, retaining selection outside the visible
page. Child-detail selections are preserved. PublicationIdentity and
InvalidateDataSource() reject obsolete publications without blocking input.
The grid owns its internal binding controller and detaches it on replacement,
clearing or disposal; callers retain ownership of their data sources.
For read-only changing collections, use the nonvisual
VisualGridArrayController<T> behind a
designer-owned grid. It reads a capture IDataSource<T> (an async collector overload
composes one) into an ArrayDataSource<T> projection with stable row identity; an
overload accepts an existing projection. It never triggers a loadable capture's
first load, binds once, serializes refreshes, queries the grid's
current page and maps the latest selected identity to its replacement in the same
native publication as the new cells, before geometry work can yield. Array
publication invalidates an older in-flight grid query so stale cells cannot be
committed against a newer selected model. Collection and worker preparation leave
the previous committed page available for input.
Typed Rows, Count, SetDefaultSort, RefreshAsync and CaptureRows
support concrete nongeneric screen surfaces. CSV/JSON export belongs to the caller.
Create/configure/refresh it on the grid's UI thread with its dispatcher context;
the capture determines its own worker execution. Late results are ignored
after grid disposal. See controller tests.
For a source that owns acquisition, configure that same source on the grid.
An array-controller overload remains for
a polled source with a necessary separate ArrayDataSource<T> view
projection, such as process hierarchy. The application or screen lifecycle
sets the polling source's Enabled and RefreshInterval, requests explicit
RefreshAsync operations and drains StopAsync when that owner closes. Source
notifications should queue a coalesced presentation refresh on the grid dispatcher.
The same overloads are available through Tools.WinForms.Grids.
Data-source change notifications
Every IDataSource<T> exposes Changed; CanNotify advertises that a source
emits it after committed data changes. A bound notifying source automatically
refreshes the current page without a loading indicator. Notification support is
independent of the grid's allowed CRUD mask, including later Capabilities
assignments. The source retains responsibility for
collection; the grid only repeats its existing filtered/sorted page query. A page
change, repaint or notification handler does not request another bulk fetch.
The source may notify from a worker. VisualGrid invalidates a pending older query immediately and coalesces presentation on its owner dispatcher. Existing rows stay interactive while new cells are prepared. Query values, column widths and configured stable selection identities survive. An active cell or modal entity draft defers the update until editing ends. Source replacement, clearing and disposal detach the subscription without disposing a borrowed source. Reference dropdowns inherit the same behavior and keep their popup open during selected-instance reconciliation.
VisualGrid owns this subscription and uses
Throttle.ExecuteAsync with a zero
interval to coalesce continuous updates without waiting for a quiet period.
Other controls keep subscriptions with their existing screen or control owner.
That owner checks its native handle, visibility and actual local-host selection,
retains a pending change while inactive, and dispatches presentation through
InvokeAsyncEx. Detach on removal or disposal without disposing borrowed sources.
Keep collection cadence and acquisition with the source's existing owner.
References from a data source
Assign a VisualGridReferenceBinding<TEntity> to a column's ReferenceBinding to select an existing record from a CRUD dropdown. Set PropertyName to the entity's property name so the default edit dialog uses the same picker:
var ManagerBinding = new VisualGridReferenceBinding<Employee>(EmployeeDataSource, EmployeeColumns,
Employee => $"{Employee.FirstName} {Employee.LastName}");
var ManagerColumn = new VisualGridColumn<Employee> {
ColumnName = "Manager",
PropertyName = nameof(Employee.Manager),
DataType = typeof(Employee),
DisplayType = VisualGridCellDisplayType.DropDownList,
PropertyValue = Employee => Employee.Manager,
SetPropertyValue = (Employee, Value) => Employee.Manager = (Employee)Value,
CanEditCell = true,
ReferenceBinding = ManagerBinding
};
The picker is read-only, automatically fits complete rows, and supports paging, search, and sorting when the data source supports them. Create, edit, delete, and action columns are omitted. Selecting a row assigns that exact record; Clear assigns null when allowed, and Cancel or Escape preserves the current reference. Set AllowNull = false to remove Clear. DropDownSize (also exposed as MaximumDropDownSize) sets the popup's content size in device pixels, defaulting to 760 × 380 and capped to the available screen space. The grid fills the popup. Search, paging, and empty results keep its dimensions stable; manual resizing lasts for that open picker.
Set ExpandsToFit = true on the column that should occupy spare width, such as the Name column in a reference picker. Other columns keep their initial measured widths. Multiple configured columns share extra space; none stretch implicitly when no column is configured. Resizing redistributes spare width from remembered minimum widths. Explicitly resized columns retain the chosen width and leave automatic stretching. Pages, search and refresh do not remeasure columns from their new values. Existing columns wider than the viewport use horizontal scrolling. Automatic page sizing continues to fit complete rows in the available grid height.
VisualGridColumn.MinimumWidth (logical pixels, 0 by default) is the narrowest width natural sizing gives a column. Natural sizing measures only the rows the grid shows, so a tree whose top-level rows leave a column empty (made parent rows over a KeyedHierarchyDataSource<T>, for example) sets it on the value columns its nested rows fill. A width the user drags is not limited by it. VisualGridColumn.MaximumWidth is the widest: a column of a few very long values, such as joined hardware IDs, would otherwise push the other columns out of view. Longer values are cut, and ExpandsToFit still widens the column to fill the grid.
Screen Options controls displayed column order through its Columns collection and exposes Manual width and Stretch to fit under each declared column. The latter overrides the binding's ExpandsToFit; clearing it restores the binding's default. A manual width takes precedence over stretch. Accepted screen settings update the visible columns and survive refresh. Configuration editing and persistence stay with the screen; the grid retains its ordinary paging, search, sorting and column interaction.
Set Hidden = true on a column that the grid should omit by default, such as an optional detail column. Each declared column also has a Hidden choice in Screen Options, which overrides the binding in either direction, and clearing it restores the binding's default. A hidden column has no native column, so it takes no width and cannot be the sort column, although the source still searches it and the default entity editor still uses its reference binding. It keeps its place in the Columns collection, together with its width and stretch choices, and reappears there when shown. GridBindings returns the complete declared schema in presentation order, while VisibleGridBindings returns the displayed columns in native column order. Use VisibleGridBindings to map a binding to a native column index. A grid that mirrors another grid's displayed columns, such as a child table, receives the parent's VisibleGridBindings and sets ShowHiddenColumns = true so that it shows every binding it is given.
VisualGrid.ReferenceBindings and VisualEntityEditor.ReferenceBindings also accept bindings keyed by a property path, such as "Manager" or "Address.Contact". The grid supplies its own data source automatically for properties whose type matches the edited entity type and which have no custom editor or converter. Explicit bindings take precedence. This avoids expanding recursive entity relationships while ordinary nested values such as Address remain editable.
VisualGridDropDown uses the same column configuration. Its MaximumDropDownSize and optional SetParametersAsync(size: ...) configure the popup size, capped to the available screen space. Use ExpandsToFit in its grid bindings to choose which columns fill spare width.
Default entity editor
The default property-grid editor remains enabled for read-only inspection, so users can select, expand and copy values. Its session-local descriptors mark all fields read-only and suppress mutating custom/collection editors when create/update capability is absent; model metadata is not changed globally. Writable editing sessions retain their existing nested/custom-editor behavior.
The default CRUD dialog expands ordinary reference properties such as Address into editable child rows without requiring attributes on the model. Existing interface and abstract instances can also be expanded. Writable concrete types with public parameterless constructors offer (Create new) and (none) choices. Circular references stop expanding when they reach an object already shown in the current path.
Nested changes retain object identity. Cancel restores edited values on the original objects, including shared references. Save accepts the new baseline only after persistence succeeds, so a failed save can still be cancelled. Change events report full paths such as Address.Street.
Custom converters, editors, and read-only metadata remain in use. Custom editor rollback covers editable object properties and IList membership. Applications needing domain-specific reference selection or factories, mutable collection-item editing, or opaque state should provide an IVisualEntityEditor implementation.
DatabaseConnectionPanel
Dynamic database connection UI that loads appropriate controls based on selected provider:
using Sphere10.Framework.Windows.Forms;
using Sphere10.Framework.Data;
public class MainForm : Form {
private DatabaseConnectionPanel _connectionPanel;
public MainForm() {
InitializeComponent();
_connectionPanel = new DatabaseConnectionPanel();
// Optionally hide certain database types
_connectionPanel.IgnoreDBMS = new[] { DBMSType.FirebirdFile };
// Handle DBMS type changes
_connectionPanel.DBMSTypeChanged += OnDBMSChanged;
Controls.Add(_connectionPanel);
}
private void OnDBMSChanged(DatabaseConnectionPanel sender, DBMSType newType) {
// Panel automatically loads correct connection UI:
// - SQLServer: MSSQLConnectionPanel
// - Sqlite: SqliteConnectionPanel
// - Firebird: FirebirdConnectionPanel
// - FirebirdFile: FirebirdEmbeddedConnectionPanel
}
private async void TestConnection() {
var result = await _connectionPanel.TestConnection();
if (result.IsSuccess) {
MessageBox.Show("Connection successful!");
// Get the DAC for database operations
// The DAC is not disposable; a scope owns the connection
var dac = _connectionPanel.GetDAC();
using (dac.EnterScope()) {
// Use dac...
}
} else {
MessageBox.Show($"Connection failed: {result.ErrorMessages.First()}");
}
}
}
PathSelectorControl
File/folder path selection with browse button:
using Sphere10.Framework.Windows.Forms;
var pathSelector = new PathSelectorControl();
pathSelector.Mode = PathSelectionMode.File; // or Folder
pathSelector.Path = @"C:\Data\file.txt";
// User can type path or browse
string selectedPath = pathSelector.Path;
A settings or entity property marked [PathSelector(PathSelectionMode.Folder)] gets the same browse button in the entity and settings editors; see the PathSelector README.
LogOutputSelectorControl
LogOutputSelectorControl is a public, designer-editable control in Sphere10.Framework.Windows.Forms. It presents a compact unlabeled checkbox and themed log-document icon button, and can be used without depending on SystemExpert. Their tooltips are Enable/Disable Logging and Log output options. The checkbox's accessible description retains current output details; the icon opens the existing configuration details and wizard workflow.
Let the selector and its ToolStripControlHost autosize from the selector's preferred content dimensions. Old fixed widths intended for the labeled control leave unnecessary blank toolbar space. Preferred size follows the native font/DPI layout while remaining compact; the application toolbar retains its configured common row height.
Checking it for the first time opens the WinForms wizard: choose File, Windows Application Log, Screen, Standard Output or Standard Error, then configure the applicable destination, levels, timestamping and Remember After Close option. Each bold destination name has an adjacent explanation. Windows Application Log uses the running application's supplied diagnostics logger. File output supports append/rolling files, encoding, retained file count and maximum encoded bytes. The checkbox turns on only after Finish validates and opens the selected output. After acceptance, unchecking stops output and checking again reuses those options. ... (Configure Log Output) opens LogOutputConfigurationDialog, showing the current details, Start Logging / Stop Logging, and Change to launch the wizard. Cancelling a change preserves the current output; a failed Finish attempts to recover the old output when reopening it is possible.
using Sphere10.Framework;
using Sphere10.Framework.Windows.Forms;
// Supply the owning application's borrowed logger for Windows Application Log.
logOutputSelector.ApplicationLogger = application.Logger;
// Bind LoggingStarting/LoggingFailed before restoring a possibly enabled output.
logOutputSelector.RestoreSettings();
await logOutputSelector.ConfigureAsync(this);
// Resolve the current logger for each write; inactive output is a NoOpLogger.
logOutputSelector.Logger.Info("Monitoring started"); // Also safe from workers.
await logOutputSelector.StopLoggingAsync();
Logger returns a NoOpLogger while off and changes to the accepted session when on. Retrieve it per write or supply a callback to a long-lived service; a logger captured while off remains inactive. Closed sessions safely ignore late calls. File writers/sinks are owned and writes join before disposal. Application loggers and console writers are borrowed and retain their existing owners/options; their callbacks run outside the session scope and their owner controls in-flight completion. Reading the property, construction and design-mode loading perform no file IO.
For capture on a UI thread, EnqueueInfo(message) queues output without file IO or a UI dispatch wait. It is also safe from workers. It returns false while off or when its session's backlog reaches 512 entries or 1 MiB of message characters; callers can count rejected captures. FlushLoggingAsync() joins entries already accepted by the current output. The checkbox's Off action, wizard changes and StopLoggingAsync() drain accepted queued entries before closing owned output. DisposeAsync() must begin on the UI thread: it detaches the sink and disposes the control immediately, preserving the remembered enabled choice, and returns a drain that completes independently of a later native message loop. Await or retain that completion in the owner's cleanup path. Synchronous StopLogging() / Dispose() retain their compatibility behavior of joining owned file IO without joining borrowed UI callbacks.
For records that already contain their capture timestamp, use EnqueueInfo(message, includesTimestamp: true). This bypasses the optional session processing-time prefix for that record; ordinary messages still follow the selected timestamp option.
Screen opens the reusable LogScreen through the actual application screen host, undocked by default. A host restricted to a single view uses an independent detached host to preserve the originating screen. ScreenHost can supply a borrowed host explicitly, including for controls contributed through a ToolStripControlHost; ordinary hosted controls resolve their screen or containing frame. ScreenTitle supplies the source name for the title Log Output - <NAME>; empty or generic names derive from the owning screen, active host screen or window, with Capture as the standalone fallback. An existing Log Output - prefix is not repeated. A standalone control also uses its own native screen host and detached window. Stopping output leaves the log readable; closing the active log view stops that selection. Hosted log views remain owned by their host after the originating selector closes. The standalone fallback closes with its selector. The bounded screen writer posts to its UI without synchronous dispatch or a permanent worker, drops after destruction, survives docking/handle recreation, and adds no timestamp beyond the selected formatting.
Hosted log views retain the originating navigation block, including after the source closes. Selecting an auxiliary screen without a block preserves the current navigation pane. Each log view retains at most 1,048,576 displayed characters and 262,144 pending characters, removing older text as needed. Destruction or direct disposal clears both buffers.
Configuration is a defensive LogOutputConfiguration snapshot. Configure/start/stop on the creating UI thread. StartLogging() accepts its already configured values for programmatic consumers; ConfigureAsync(owner) supplies the wizard and ShowConfigurationAsync(owner) supplies the details dialog. LoggingStarting(configuration) can veto before IO, including during restoration. LoggingStateChanged, LoggingFailed, HasConfiguration, IsLogging and LastError expose state and failures. Do not separately dispose the selected session or register it as another global owner.
With Remember After Close, LogOutputSelectorSettings persists the accepted configuration and enabled choice through UserSettings. Call RestoreSettings() explicitly after the application logger and consumer hooks are ready. Construction/handle creation never read preferences or open output. The method returns false while a stable owner/provider is unavailable and can then be retried; completed restoration is idempotent. RestoreSettingsAsync(cancellationToken) does the same but reads the settings store on a worker, so a slow store does not hold the UI thread, and then applies the values and resumes remembered output on the owning thread; a call while a read runs joins it. SettingsKey can supply an explicit stable ID; otherwise the owning screen/control type and named child path identify this selector independently of captions or docking. Set the key before restoring or accepting output. Restoration and unchanged disposal do not write preferences, and disposal closes a remembered active sink without changing its saved enabled choice. Turning Remember off deletes only that selector's stored preferences, including its cached record. Optional preference failures appear in LastSettingsError; output remains usable and failed accepted saves retry on disposal. See per-user UI settings.
Hosted screens bind a LogOutputSelectorPreferences property on their actual ScreenSettings object through BindLogOutputPreferencesAsync, for example nameof(MyScreenSettings.LogOutput). A non-null selector Preferences selects screen ownership. CapturePreferences() returns configuration and the remembered Enabled choice; ReadLegacyPreferencesAsync(provider) reads existing standalone values without creating a record or opening output. Binding may import those values before the screen has its first typed settings record. Subsequent edits update the actual root object, and its successful SaveAsync() raises OnChanged for the screen and Options consumers.
ApplyPreferences(values) is a pure value/UI operation: the selector must be stopped and its drain awaited first. It neither starts logging nor saves preferences. The real owning screen supplies its application logger and preflight before explicitly starting remembered enabled output. Accepted configuration and On/Off changes raise PreferencesChanged through the overridable OnPreferencesChanged hook; disposal does not invent an Off preference. Output choices with Remember After Close disabled remain available in the current session but their configuration/enabled fields are omitted from the root's JSON persistence. Standalone RestoreSettings() and its existing Remember/delete/preflight behavior remain available when no screen owner is assigned.
SystemExpert's watcher passes eventLoggerProvider: () => logOutputSelector.Logger, so output changes take effect without restarting monitoring. Every accepted event is independent of display filters, pause and retention; file paths inside the watched tree are rejected before IO. WinFormsTester's Logging screen demonstrates the selector alongside a TextBoxLogger preview. See the reusable controls catalog.
ToolStripChoiceSelector
ToolStripChoiceSelector displays a fixed set of toolbar choices as a native
button and checked menu, without an editable text field. Call SetItems with the
original data objects, set SelectedItem or SelectedIndex, and handle
SelectedIndexChanged. Items returns copied array membership; menu tags and the
selection retain the original objects. Replacement preserves a matching reference
before falling back to value equality. ItemTextProvider formats captions and
EmptyText names the unselected state. Menu click and keyboard selection use the
same event path. The selector owns its menu items and borrows the data objects;
disposal clears its retained choices without disposing them. It fits its widest
choice rather than the selected one, so the toolbar does not move when the
selection changes, and its height follows the font, so it scales with the display.
Leave AutoSize on; a fixed width stays in 96-DPI pixels and cuts the text on a
scaled display. A list of unbounded names, such as event log channels, sets
MaximumWidth in logical pixels and longer choices are cut.
ToolStripCommandMenu
ToolStripCommandMenu is a menu whose entries mirror toolbar commands as they are
when the menu opens. A screen that already owns a toolbar can offer the same
commands from the application's menus without a second set of handlers. Choosing
an entry clicks the command it mirrors, so the command keeps one caption, image,
enabled and checked state:
var view = new ToolStripCommandMenu("View");
view.AddCommands(refreshButton, pauseButton);
view.AddSeparator();
view.AddCommand(modeSelector, "CPU Sample View"); // a selector's text shows its value, so name the entry
menuStrip.Items.Add(view);
screen.ScreenMenuStrip = menuStrip; // merged while the screen is active
Buttons become entries, drop-down buttons and choice selectors become submenus of
their own items, and a split button leads its alternatives with its own action.
Hidden commands, labels and hosted controls have no entry; a disabled command has
a disabled one. Leading, repeated and trailing separators are dropped. EmptyText
is the disabled entry shown while no command is available. The commands are
borrowed and may live on any strip or on none. RefreshCommands rebuilds the
entries on demand; opening the menu calls it, including when the menu's heading
has been merged into another strip's heading of the same caption.
Start/stop buttons
ToolStripStartStopButton and StartStopButton are one command for an operation
that is either stopped or running. While stopped they show a green start triangle
with StartText; while running they show a red stop square with StopText, so
only the command that applies is on screen. The owner sets Running when the
operation's state changes. A click raises StartRequested or StopRequested and
changes nothing else, so a declined or failed start leaves the button as it was:
var capture = new ToolStripStartStopButton { StartText = "Start Capture…", StopText = "Stop Capture" };
capture.StartRequested += StartCapture;
capture.StopRequested += StopCapture;
toolbar.Items.Add(capture);
// When the operation reports its state
capture.Running = status.IsCapturing;
The tool strip button also takes StartToolTipText and StopToolTipText. Both
controls draw their glyphs in code and own them. StartStopButton draws its glyph
again at the display's size after a DPI change.
ProgressBarEx
Enhanced progress bar with text display:
using Sphere10.Framework.Windows.Forms;
var progressBar = new ProgressBarEx();
progressBar.DisplayStyle = ProgressBarDisplayText.Percentage;
progressBar.Value = 75; // Shows "75%"
ValidationIndicator
Visual validation state indicator:
using Sphere10.Framework.Windows.Forms;
var validator = new ValidationIndicator();
validator.State = ValidationState.Valid; // Green checkmark
validator.State = ValidationState.Invalid; // Red X
validator.State = ValidationState.Pending; // Yellow
RadioGroupBox
Group box with built-in radio button management:
using Sphere10.Framework.Windows.Forms;
var radioGroup = new RadioGroupBox();
// Radio buttons inside are mutually exclusive
ServiceStatusControl
Display Windows service status:
using Sphere10.Framework.Windows.Forms;
var serviceStatus = new ServiceStatusControl();
serviceStatus.ServiceName = "MyService";
// Displays: Running, Stopped, Starting, etc.
Application banners
ApplicationBanner is the concrete
designer surface for product title, version and company branding. Extend it with
a product-owned subclass and designer pair, then register that subclass as the
transient ApplicationBanner service. Framework registers the stock transient
only when no application registration exists.
Place ApplicationBannerHost in a
form's designer to opt in to that registration. It retains a static stock preview
on the design surface and resolves Banner on runtime load or first access.
Each host requires its own transient instance and owns that child through its
control collection, disposing it with the host.
The banner owns its rendered icon bitmaps, releases replaced images during
resizing and disposes its final image with the control. The icon supplied by
IApplicationIconProvider remains borrowed from that provider.
UseIcon(icon) selects that application's borrowed icon; retain it for the
runner's complete lifetime. AddMainForm preserves an explicitly registered
IApplicationIconProvider. Its default provider uses the configured icon, then
the main form's ApplicationIcon contract. The native runner applies the
resolved icon to the main window before initialization, and the standard About
dialog uses the same provider for its title bar and banner. Consumers must not
dispose the shared icon or allocate undisposed per-read copies. The banner uses
Drawing's aspect-fit padded resize, centered in both dimensions, and About uses
the full product version consistently. ShowAboutBox resolves its dialog from a
per-call DI scope retained through awaited modal completion. Closing disposes a
transient or scoped dialog and its rendered banner images; a custom singleton
remains owned by the application container and can be shown again.
🛠️ Tools.WinForms Discovery
Reference Sphere10.Framework.Windows.Forms for the static Tools.WinForms
helpers. Its cursor factories return new native cursors owned and disposed by
the caller.
// Create custom cursor from bitmap
Cursor cursor = Tools.WinForms.CreateCursor(bitmap, hotspotX, hotspotY);
// Load cursor from raw bytes
Cursor rawCursor = Tools.WinForms.LoadRawCursor(cursorBytes);
Discover reusable native components
Tools.WinForms is a static partial class in this assembly, with a nested static
class for each domain. Reference this library and call its factories directly to
create native controls. The Windows assembly has no dependency back to Windows
Forms. Scope factories such as Tools.Scope.EnterRenderingScope are contributed
separately by WinFormsScopeExtensions through C# static extension members;
import using Tools; for those scope calls.
The utility groups return the existing concrete types with their normal defaults. No group stores a control, starts capture or creates an application host. Constructors and direct APIs remain available for designer-authored UI.
| Group | Entry points |
|---|---|
Tools.WinForms.Windowing |
CreatePicker(dispatcher) returns a one-use WindowPicker. The dispatcher needs a live native handle. Highlighting already uses Tools.Scope.EnterHighlightScope(physicalBounds, color, thickness). |
Tools.WinForms.Charts |
CreateGraphChart, CreateBarChart, CreateTelemetryChart and CreateChart return fresh chart surfaces. CreateLogOutputBehavior attaches the existing behavior to a bare DataVisualization chart; the three wrapper controls already own their logging behavior. FormatLogSample delegates the existing UTC/title/readings formatter without creating UI. |
Tools.WinForms.Logging |
CreateOutputSelector returns an inactive LogOutputSelectorControl. RegisterOutputLifetime forwards cleanup registration to the current application's existing LogOutputLifetime service and returns null when that service is unavailable. |
Tools.WinForms.Grids |
CreateVisualGrid, capture and passive-projection CreateArrayController overloads, CreateDataSourceDetail and CreateControlDetail expose the existing projection and owned-panel adapters. Configure a ranged source directly on its grid. |
Tools.WinForms.Review |
CreateHexEditor, ShowBytesAsync, EditBytesAsync and ShowTextAsync expose the byte editor and existing owned modal review/save workflows. |
Tools.WinForms.Controls |
CreateChoiceSelector and CreateSearchBox return the shared non-editable toolbar selector and textbox with inline clear action. |
Create, configure and dispose native controls on their owning UI thread. The caller or containing control owns a factory-created control; source/collector factories do not add a worker boundary or change ownership of borrowed inputs. Row-detail adapters take ownership of the fresh child controls and supplied resources. Keep paging, column settings, row details and capture policy in the existing owner. There is no parallel row-details builder or settings record.
WindowPicker owns its input hooks and one selection lifetime; dispose it on
the dispatcher thread after awaiting PickAsync. A chart logging behavior
borrows its chart; dispose the behavior and await its Completion or
DisposeAsync before ending the UI loop. Wrapper charts expose their own
LogOutputBehavior, so do not attach another behavior to their native chart.
ShowBytesAsync stages fixed-length edits and copies saved changes into the
supplied array after the window closes successfully. It returns whether changes
were saved; cancelling leaves the supplied array unchanged. EditBytesAsync
edits a copy that can grow and shrink, as a stream of any length can, and returns
the saved content or null; the supplied array is never changed. In either editor,
typing at the end of a document that can grow appends bytes, in overwrite mode too.
ShowTextAsync reviews complete text and returns a saved path or null when the
view closes. Token cancellation retains each underlying dialog's cancellation
and cleanup contract. A proxy does not silently save, truncate or reinterpret
the supplied content.
var graph = Tools.WinForms.Charts.CreateGraphChart();
var grid = Tools.WinForms.Grids.CreateVisualGrid();
var output = Tools.WinForms.Logging.CreateOutputSelector();
var choice = Tools.WinForms.Controls.CreateChoiceSelector();
// The screen or its containing controls own these instances and their lifetime.
📋 Available Components
Use the central reusable WinForms controls catalog for the full categorized selection guide, including provider-specific database editors, registration requirements, ownership and current limitations.
Controls
| Control | Description |
|---|---|
CheckedGroupBox |
Group box with checkbox header |
ApplicationBanner |
Designer-editable product title, version and company branding |
ApplicationBannerHost |
Stock designer preview with a registered transient banner at runtime |
PathSelectorControl |
File/folder path selection |
LogOutputSelectorControl |
Optional wizard-configured file/application/stdout/stderr output, configuration details dialog and remembered preferences |
ToolStripChoiceSelector |
Fixed toolbar choice through a checked native menu, retaining original data objects |
ToolStripCommandMenu |
Menu whose entries mirror borrowed toolbar commands when it opens and click them when chosen |
ToolStripStartStopButton |
One toolbar command that shows Start with a green triangle while stopped and Stop with a red square while running |
StartStopButton |
The same single start/stop command as a plain button |
ProgressBarEx |
Progress bar with text display |
PropertyGridEx |
Enhanced property grid |
RadioGroupBox |
Radio button group container |
ServiceStatusControl |
Windows service status display |
ValidationIndicator |
Visual validation state |
ExpandingCircle |
Animated expanding circle |
PictureBoxEx |
Enhanced picture box |
UserControlEx |
Enhanced user control base |
Database Components
| Component | Description |
|---|---|
DatabaseConnectionPanel |
Dynamic DBMS connection UI |
DatabaseConnectionBar |
Compact connection bar |
ConnectionPanelBase |
Base class for connection panels |
IDatabaseConnectionProvider |
Interface for connection providers |
Other
| Component | Description |
|---|---|
WinFormsActionWizard<TModel> |
Multi-step wizard with native presentation |
SourceGrid |
Advanced data grid |
LoadingCircle |
Loading animation |
ExplorerBar |
Explorer-style navigation bar |
VisualCalendar |
Appointment/calendar UI |
ApplicationBlock |
Modular application sections with menus |
Loading indicators
LoadingCircle.AnimationStyle offers Spokes, Dots, Arc and Pulse animations.
Set Color for your palette and RotationSpeed for the frame interval in milliseconds.
The existing StylePreset values and radius/spoke properties remain available for
older designer files and custom geometry. Use LoadingCircleToolStripMenuItem
when the indicator belongs in a native toolbar or menu.
loadingCircle.AnimationStyle = LoadingCircleAnimationStyle.Arc;
loadingCircle.Color = Color.Teal;
using (loadingCircle.BeginAnimationScope(editorPanel, cancelButton)) {
await LoadItemsAsync();
}
The caller retains ownership of an existing indicator. Its scope stops animation
and restores controls it disabled; controls already disabled remain disabled.
LoadingCircle.EnterAnimationScope(...) creates a temporary overlay and disposes
that owned indicator on exit. Animation uses the native UI timer and does not
publish edited-state events. The Loading Indicator screen in WinForms Tester
shows all four styles, colour choices and both scope patterns.
🏗️ Application Blocks
Application blocks provide a modular way to organize application features with menu structures. The builder pattern provides a fluent API for construction:
using Microsoft.Extensions.DependencyInjection;
using Sphere10.Framework.Windows.Forms;
// Register an application block using the builder pattern
serviceCollection
.AddApplicationBlock(
new ApplicationBlockBuilder()
.WithName("My Block")
.AddScreen<MainScreen>(screen => screen
.WithTitle("Main")
)
.AddScreen<SettingsScreen>(screen => screen
.WithTitle("Settings")
.AsSingleInstance()
)
.AddScreen<ToolA>(screen => screen
.WithTitle("Tool A")
)
.AddScreen<ToolB>(screen => screen
.WithTitle("Tool B")
)
.WithDefaultScreen<MainScreen>()
.AddMenu(mb => mb
.WithText("File")
.AddActionItem("New", () => CreateNew())
.AddActionItem("Open", () => OpenFile())
.AddShowScreenItem<SettingsScreen>("Settings")
)
.AddMenu(mb => mb
.WithText("Tools")
.AddShowScreenItem<ToolA>("Tool A")
.AddShowScreenItem<ToolB>("Tool B")
)
.Build()
);
// Or create a reusable builder method
public class MyApplicationBlock {
public static ApplicationBlock Build() {
return new ApplicationBlockBuilder()
.WithName("My Application")
.AddScreen<DashboardScreen>(screen => screen
.WithTitle("Dashboard")
.AsSingleInstance()
)
.AddScreen<Screen1>(screen => screen
.WithTitle("Option 1")
)
.AddScreen<Screen2>(screen => screen
.WithTitle("Option 2")
)
.WithDefaultScreen<DashboardScreen>()
.AddMenu(mb => mb
.WithText("Main Menu")
.AddShowScreenItem<Screen1>("Option 1")
.AddShowScreenItem<Screen2>("Option 2")
.AddActionItem("Custom Action", () => DoSomething())
)
.Build();
}
}
// Register in ModuleConfiguration
serviceCollection.AddApplicationBlock(MyApplicationBlock.Build());
Use direct arguments for compact registration and retain a moniker only when needed:
var block = new ApplicationBlockBuilder()
.WithName("Controls")
.AddScreen<FlagsCheckedBoxListScreen>("Flag Choices", out var flags, activationMode: ScreenActivationMode.SingleInstance)
.WithDefaultScreen(flags)
.AddMenuItem("Input", inputImage, showInMenuStrip: true, configure: menu => menu
.AddItem(flags, "Flag Choices", image16x16: flagsImage)
.AddItem("Reset", () => ResetChoices(), showOnToolBar: false)
)
.Build();
AddScreen<TScreen>("Title") requires no callback or moniker. Optional named arguments
cover activation mode, screen kind, stable key, typed settings/defaults, activator
and settings editor. The runtime form is AddScreen(typeof(MyScreen), "Title");
both forms can capture out var registration after the title. AddMenu and
AddMenuItem use the same owned-menu path, with optional image, menu-strip flag
and child callback. Their out forms capture the owned menu. Menu AddItem accepts
an action, generic/runtime screen type, exact moniker or existing definition, with
optional native presentation flags and command capture. Callbacks and existing
AddShowScreenItem/AddActionItem conveniences remain available. These overloads
preserve deferred activation and the native builders' retained product behavior.
Owner-aware actions receive the executing IUserInterfaceServices, including actions marked executeOnLoad:
menu
.AddActionItem("Ready", userInterface => userInterface.Status = "Ready")
.AddItem(item => item
.AsActionItem()
.WithText("Report status")
.WithAction(userInterface => userInterface.Status = "Ready")
);
The parameterless Action overload remains available. Native action items take synchronous delegates; an async lambda supplied to one becomes async void, and command dispatch cannot await its completion. Await asynchronous dialogs and other work from a Task-returning method or a native async event handler as shown above. PrimaryUIController supplies the form when a callback needs its native owner. AddItem(existingItem) registers an existing item; AddItem(item => ...) configures a child builder and adds its built item. AddShowScreenItem adds a command for an already registered screen; AddActionItem adds an action. Neither creates a screen registration. A type-based screen command selects the first matching registration in its declaring block; pass an exact registration reference when several definitions share that type.
The builder pattern supports:
- Screen items: Navigate to specific forms/screens
- Action items: Execute custom code when clicked
- Menu organization: Group related features logically
- Fluent API: Chain methods for clean, readable code
- Type-safe: Compile-time checking with generics
Grouping blocks into application plugins
The running shared UI hierarchy is Sphere10.Framework.Application.UI.IApplication → Sphere10.Framework.Application.UI.IApplicationBlock → menus and screens. Native extensions use Sphere10.Framework.Windows.Forms.IApplication, IApplicationBlock and their native menu and screen contracts. A plugin contributes startup services and any number of blocks, including zero. LoadedPlugins records those startup contributors; every contributed block has its own navigation icon and menus.
Shared applications, blocks, screens and plugins inherit IApplicationCommandProvider for
portable Menus and ToolBarItems descriptors. Native blocks project their typed
menu definitions through that contract. A main form supplies its actual
designer-owned menu and toolbar commands through IMainForm; the running
Application exposes that provider together with explicitly supplied
application contributions. Editing a main form's native menu/toolbar is enough
to publish its Exit, About, feedback and help commands. Native callbacks and
resources retain their original control/form owner.
For a screen, set ScreenMenuStrip to its designer-owned MenuStrip and
ScreenToolBar to its designer-owned ToolStrip. Its provider projects the
actual controls, and the host moves those same native items into the active
frame through the reusable merge controls, restoring their source owners on navigation or detach.
Whatever is merged, MainForm.ArrangeMenus keeps the bar in one order: File, the
View menu, Options, then the merged menus, then Screens and Help last.
Owners cache command membership through GetMenus() / GetToolBarItems() hooks;
configure membership before activation. Captions and checked/enabled state remain
live on the native items. Because merged items leave ScreenToolBar.Items while
the screen is active, a screen that must change all its own commands at once (for
example, to disable them under a cover) reads the protected ScreenToolBarItems,
which lists them wherever they are without activating command membership.
MainForm composes the host form plus the active
plugin, block and screen on demand, without command binding registries.
MergeAction / MergeIndex retain their native meaning.
ScreenToolBar replaces the previous screen ToolBar property. Legacy
RegisterMenuItem/MenuItems consumers retain their existing native path.
In your existing module's RegisterComponents(IServiceCollection serviceCollection) method, group blocks with the native plugin builder:
using Microsoft.Extensions.DependencyInjection;
using Sphere10.Framework.Application;
using Sphere10.Framework.Application.UI;
using Sphere10.Framework.Windows.Forms;
serviceCollection
.AddWinFormsApplicationPlugin(plugin => plugin
.WithName("Administration")
.AddInitializer<AdministrationInitializer>()
.AddFinalizer<AdministrationFinalizer>()
.AddServices(services => services.AddSingleton<AdministrationService>())
.AddBlock(block => block
.WithName("Administration")
.AddScreen<DashboardScreen>(screen => screen
.WithTitle("Dashboard")
.AsSingleInstance()
)
.AddScreen<SettingsScreen>(screen => screen
.WithTitle("Settings")
.AsSingleInstance()
)
.WithDefaultScreen<DashboardScreen>()
.AddMenu(menu => menu
.WithText("Management")
.AddShowScreenItem<SettingsScreen>("Settings")
)
)
);
AdministrationService, DashboardScreen and SettingsScreen are application types; screens derive from ApplicationScreen. The lifecycle types can use the root's logger and application-owned dependencies:
using System.Threading;
using System.Threading.Tasks;
using Sphere10.Framework.Application;
using Sphere10.Framework.Application.UI;
using SharedUI = global::Sphere10.Framework.Application.UI;
public sealed class AdministrationInitializer : AsyncApplicationInitializerBase {
private readonly SharedUI.IApplication _application;
public AdministrationInitializer(SharedUI.IApplication application) => _application = application;
public override Task InitializeAsync(CancellationToken cancellationToken = default) {
cancellationToken.ThrowIfCancellationRequested();
_application.Logger.Info("Administration components are ready.");
return Task.CompletedTask;
}
}
public sealed class AdministrationFinalizer : AsyncApplicationFinalizerBase {
private readonly SharedUI.IApplication _application;
public AdministrationFinalizer(SharedUI.IApplication application) => _application = application;
public override Task FinalizeAsync(CancellationToken cancellationToken = default) {
_application.Logger.Info("Administration components are finalized.");
return Task.CompletedTask;
}
}
Replace these demonstration messages with the plugin's actual startup and cleanup work. For a reusable definition, call new ApplicationPluginBuilder()...Build() and pass its result to AddWinFormsApplicationPlugin(plugin). AddBlock(block => ...) builds a nested block; AddBlock(block) registers an existing IApplicationBlock.
Registration invokes Load(IServiceCollection) once, validates the completed contribution, and supplies its blocks to the existing AddApplicationBlock startup path. Only after those registrations succeed does it publish an ApplicationPluginRegistration<IApplicationPlugin> receipt containing the original plugin and a defensive copy of its contributed block membership. The application factory reads these receipts; manually registering an unloaded plugin in DI does not add it to LoadedPlugins. Failed loading or contribution validation does not publish a receipt. Later changes to a plugin's block getter do not change the captured startup contribution.
Registration rejects both duplicate successful plugin names and recursive attempts to load the same name. A failed registration discards newly added lifecycle task descriptors under the attempted name, preventing a later successful plugin with that name from inheriting abandoned tasks. Ordinary AddServices side effects retain their existing behavior.
The same plugin instance remains available through native and shared DI contracts. Application.Initialize() and await Application.InitializeAsync() register each native block once, retaining position ordering, default screens and ExecuteOnLoad behavior. Startup selection follows receipt and block declaration order, while Position orders the navigation icons. Resolving or disposing an application adapter does not load, unload or dispose plugin definitions. Block objects, menu parent links, images and disposal ownership remain with the existing native code.
ApplicationPlugin uses ApplicationPluginBase<IApplicationBlock> and retains compatibility with the shared Sphere10.Framework.Application.UI.ApplicationPlugin, including typed virtual Blocks overrides. Shared screen-host projections live in the generic interfaces. Native hosts and decorators inherit the shared mutable ScreenMode contract; virtual overrides dispatch through both shared and native views.
Existing AddApplicationBlock calls and the Application(form, blocks) constructor remain supported. Their blocks appear directly in the application's live Blocks array without creating a plugin. The three-argument constructor accepts loadedPlugins that the caller has already loaded and captures their contributions without invoking lifecycle methods. Successfully registered plugin names must be unique, and a block reference cannot be contributed by two plugins.
IApplication.LoadedPlugins returns a snapshot of the original loaded plugin instances. Blocks projects the host's current registered blocks and follows direct registration and guarded removal. Removing a contributed block does not unload its plugin. Browse navigation through ScreenHost.SelectBlock and perform screen operations through the host; plugins have no active UI selection. The shared IApplication resolves to the same application object and projects the same loaded plugins and live blocks. The selected block's navigation pane is rebuilt on demand.
Leaving a block out of an application
AvailableWhen(services => ...) on ApplicationBlockBuilder supplies a predicate that decides whether this application offers the block, for example from its licensed edition:
using Microsoft.Extensions.DependencyInjection;
using Sphere10.Framework.Windows.Forms;
var block = new ApplicationBlockBuilder()
.WithName("Administration")
.AvailableWhen(services => services.GetRequiredService<AdministrationService>().IsEnabled)
.AddScreen<DashboardScreen>("Dashboard")
.Build();
IsEnabled is a member of your own AdministrationService. The builder builds an ActionApplicationBlock, the ApplicationBlock subclass that takes the predicate in its constructor; construct one directly for a block without a builder. A block subclass decides instead by overriding the protected DetermineAvailability(IServiceProvider) hook, and the host asks through the public CheckAvailability(IServiceProvider). Configure AvailableWhen before Build: the retained block's availability is fixed when it is built, so a later call throws InvalidOperationException. The screen host evaluates the predicate once, with the application's service provider, when the block is first offered for registration, and it keeps that answer while the main form lives. Startup registration and IBlockManager.RegisterBlock skip a block that declined. It gets no navigation button, its ExecuteOnLoad items and permanent screens do not run, and startup selection continues with the next block. ScreenHost.RegisterBlockAsync rejects it. A predicate that throws fails application initialization. The predicate needs the provider that UseMainForm or AddMainForm attaches to the main form, or the one the Application was constructed with. A block without a predicate is always offered.
Availability is presentation only. It authorizes nothing, so the application's services must still enforce the licence or permission themselves.
Native command context
A detached window projects the application's original native commands alongside its own active plugin, block and screen. The main form retains its controls, images and callbacks; each detached window owns its generated views. Command membership is captured recursively at owner activation, including nested menus, while captions and checked/enabled state stay live. The Screens menu adds current navigation entries to its original application commands.
In a derived MainForm handler, capture
var userInterface = CommandUserInterfaceServices; before the first await.
Capture userInterface.ScreenHost?.ActiveScreen there too when the operation
targets that screen. This protected property supplies the invoking window's UI
context during the original native callback; the context is restored when that
callback returns. A detached invocation does not change the main form's active
screen. The original designer event handlers still run once.
Keep popup availability logic in the original DropDownOpening handler. The
generic merge controls forward preparation for matching headings, return the
source's children while it prepares them, and merge the prepared children back.
Detached projections run the original preparation without displaying the main
form's popup. This also applies when a screen supplies a matching Options or
Screens heading.
Screen Options
Declare a public nested SettingsObject subclass inside the screen it configures,
and declare [Settings(typeof(...))] on the screen class. An optional covariant
ScreenSettings override provides typed access; mark that property
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)].
AddScreen<UsersScreen>("Users") discovers the declared type before constructing
the control. Existing [UseSettings(typeof(...))] metadata remains supported.
UseSettings(actualSettings) supplies an actual instance for a particular
registration, including independent CPU/GPU registrations of the same screen type.
Attribute, property and explicit builder schemas must agree; a clash throws.
Declare reset defaults with [DefaultValue(...)] on settings members.
RestoreDefaultValues() applies those attributes to the actual instance; override
that existing method for domain-specific nested values, such as resetting a grid's
layout while retaining its column identities. Constructor or registration-time
assignments are initial values, and do not become a separate stored reset baseline.
Blocks and plugins expose their actual BlockSettings and PluginSettings
objects and accept them through their builders' UseSettings methods. Screens read
those same instances through GetBlockSettings<T>() and GetPluginSettings<T>().
IApplication.Settings exposes the existing ISettingsProvider, with native
applications using ISettingsServices.UserSettings and their configured user-provider
fallback. Startup loads declared values before screen activation, retaining the
supplied root identities and existing provider IDs. Screen registrations without
an explicit ID use a stable identity derived from their application, owner and
registration keys.
Keep screen initialization in InitializeUIPrimingData, CopyModelToUI and
CopyUIToModel. Bind grid and log settings before the first query through the
screen's awaited initialization task. ApplicationControl listens directly to the
actual screen, block and plugin settings objects' OnChanged events and uses the
existing Refresh() lifecycle on the UI thread. Handle recreation reapplies current
values, and disposal removes those subscriptions. SettingsObject.Save() and
SaveAsync() notify listeners after their existing provider successfully persists
the actual object. Cache and encryption behavior remain with that provider.
Options enumerates existing plugin, block and screen-definition owners, including
unopened screens with settings. Screens without settings are omitted. Opening
Options prefers the active screen's settings unless the caller requests an owner;
existing block/first-page selection remains the fallback. It supplies the selected owner's actual settings object to a
registration-specific editor, the class's [Editor] editor, or the [UserEditable]
automatic editor, in that order. [UserEditable] marks the class; public properties
are eligible for editing, and [Transient] excludes runtime members from editing
and storage. Hidden or readonly presentation attributes retain their persistence
meaning.
Apply validates the actual object and awaits SaveAsync(). Cancel restores local
dialog backups for unapplied edits while retaining earlier successful Apply
operations. Reset confirms its impact and calls RestoreDefaultValues() on the
selected owner's settings and descendants by default, including settings without
editors. Defaults remain provisional until Apply/OK. The native dialog's Policy
uses the ApplicationSettingsScreenPolicy flags ResetDescendants,
IncludeNonEditableSettings and ApplyPendingResetScope; Default combines all
three. None limits Reset to the selected editable page and Apply to the selected
page. Default Apply saves pending resets across navigation; OK always saves all
pending reset pages. Unrelated manually edited pages retain their existing rules.
See the native reset policy table and the complete
native pattern and
Screen Options.
Remembering the main window
Enable automatic per-user window settings at application startup:
using Sphere10.Framework;
using Sphere10.Framework.Windows.Forms;
Sphere10Framework.Instance
.BuildWinFormsApplication()
.UseMainForm<BlockMainForm>()
.UseMainFormSettings()
.StartWinFormsApplication();
UseMainFormSettings() restores the main window's normal bounds, monitor and maximized state, captures placement after all exit permissions approve shutdown, and writes it once through a framework shutdown task before the window closes and settings providers are disposed. The later FormClosed event does not queue another save. Moving, resizing, and dragging the menu divider do not write settings. Cancelled exit requests do not queue a save. A minimized window reopens in its last normal or maximized state. Missing monitors and changed working areas or DPI are handled by fitting the window onto an available display. Without saved settings, the configured initial size is used.
BlockMainForm also saves the left navigation pane's width in the same FormWindowSettings, including its last expanded width while collapsed or temporarily hidden. The restored width scales with DPI and is clamped to the current navigation limits. With no saved width, the wider default applies.
FormWindowSettings uses the existing UserSettings provider and SettingsObject.Save() contract. The default settings ID is "MainForm"; supply SettingsID to distinguish multiple main-window configurations. UseMainFormSettings(false) disables automatic persistence. Optional preference read/write failures are logged and do not prevent opening or closing the application.
Other forms can keep Tools.WinForms.AutoPersistWindowSettings(Form, SettingsID) in a using scope for the window's lifetime to save once on accepted closure, or use CaptureWindowSettings and RestoreWindowSettings with their own FormWindowSettings instance. See the user UI settings practice for settings classes, defaults, lifecycle and storage conventions.
Shared presentation contracts
The portable contracts and implementation state live in Sphere10.Framework.Application.UI. Native implementations live in Sphere10.Framework.Windows.Forms, with names such as ApplicationScreen and ApplicationBlock. Where shared and native names overlap, qualify the shared contract or use using SharedUI = global::Sphere10.Framework.Application.UI;. Keep native message-loop calls qualified as System.Windows.Forms.Application. ScreenActivationMode comes directly from the shared namespace; there is no separate native enum. WinForms IApplicationBlock specializes the shared menu and toolbar provider with native descriptor types. IApplicationMenu, IApplicationMenuItem and IWinFormsScreenMenuItem extend standalone shared presentation contracts with native options. IApplicationScreen exposes designer-owned ScreenMenuStrip and ScreenToolBar controls; their commands project through the inherited portable provider alongside lifecycle, ownership and help. Custom blocks supply ScreenDefinitions and DefaultScreenDefinition; custom screen items supply a canonical ScreenDefinition reference. Shared navigation has no menu string IDs. Screen registrations have block-local identity; WithStableKey gives a registration a deliberate persistent key. ApplicationBlock and ApplicationMenu derive from abstract ApplicationBlockBase and ApplicationMenuBase<TItem>. ApplicationMenuItemBase and WinFormsLinkMenuItemBase are abstract native intermediates above the concrete screen and action items. Native APIs retain images, menu parents, array views and disposal ownership. The fluent native builders inherit block-owned screen registration and child-builder composition from typed shared bases, then create WinForms products on the first Build(). Plugin AddBlock, block AddScreen/AddMenu, menu AddItem and common setters live in Sphere10.Framework.Application.UI; native adapters retain images, menu/explorer/toolbar flags and control factories. Subsequent builds return the same product and incorporate additional canonical definitions. Later name, position, default and menu configuration updates the existing native product, preserving one owner for menus, items and images.
IApplicationScreen extends the shared Sphere10.Framework.Application.UI.IApplicationScreen contract with synchronous native hooks. ApplicationScreen maps those hooks to its existing display and cancelable hide events on the calling UI thread. Shared CanDeactivateAsync invokes the native hide guard; OnDeactivatedAsync does not emit the hide notification again. Cancellation is checked before invoking a native hook. The native presentation hooks remain synchronous; the host also exposes the shared asynchronous operations for controls, tabs, docking and screen disposal.
Screen definitions carry activation modes for both UI hosts. The native adapter uses the shared ScreenActivationMode enum directly. Each registration resolves its own mode; menu commands carry presentation and a registration reference. When a registration omits a mode, its first constructed screen supplies the fallback, and subsequent instances of that registration must agree. Help metadata remains available through the shared screen contract.
Running application and shared wizards
IApplication : Sphere10.Framework.Application.UI.IApplication exposes the running BlockMainForm through live blocks, loaded startup plugins, its screen host, retained unsaved state and change notifications. The host exposes SelectedBlock for navigation browsing and ActiveBlock for the
visible screen's owner, with the selected block as a no-screen fallback. A detached
screen has a local host adapter with its own active context; navigation and
application lifetime delegate to the originating root host. For BlockMainForm and its subclasses, AddMainForm registers the native and shared interfaces to the same adapter; framework startup initializes its configured blocks. The adapter borrows the form and screen host rather than creating a second owner. SetMenus and SetToolBarItems accept native command definitions and update the actual application menu and toolbar before command activation. The owner caches their membership; the form rebuilds
the current native presentation through its merge controls and original callbacks.
Command composition follows the visible ActiveScreen.Block and its plugin;
sidebar selection does not contribute commands. Without an active screen, only
application commands remain in the main menu and toolbar.
WinFormsWizardBuilder<TModel>, WinFormsActionWizard<TModel>, IWinFormsWizard<TModel>, WinFormsWizardScreen<TModel> and WinFormsWizardDialog<TModel> replace the unprefixed native wizard names. Navigation, step membership, callbacks and completion policy use the shared Application.UI wizard workflow; native adapters retain control initialization, validation, presentation, sizing and disposal. Dynamically removed screens remain owned by their wizard and are disposed with it. WizardResult, WizardStepUpdateType and ScreenMode now come directly from the shared UI namespace.
Multiple screens and detachable tabs
The cross-platform host guide maps these operations to Blazor, including startup preferences, retained sessions, close guards and the native detached-window boundary.
MainForm.ScreenMode defaults to ScreenMode.SingleView, which shows one screen without a tab bar. Set it to ScreenMode.MultiView to keep multiple screens open in titled tabs. BlockMainForm inherits this property and hosts the tabs in its main content panel.
using Sphere10.Framework;
using Sphere10.Framework.Application.UI;
using Sphere10.Framework.Windows.Forms;
var block = new ApplicationBlockBuilder()
.WithName("Workspace")
.AddScreen<DashboardScreen>(screen => screen
.WithTitle("Dashboard")
.AsSingleInstance()
)
.AddScreen<EditorScreen>(screen => screen
.WithTitle("Editor")
.AsMultiInstance()
)
.AddScreen<ReportScreen>(screen => screen
.WithTitle("Report")
.AsMultiInstance()
)
.WithDefaultScreen<DashboardScreen>()
.AddMenu(menu => menu
.WithText("Views")
.AddShowScreenItem<DashboardScreen>("Dashboard")
.AddShowScreenItem<EditorScreen>("New editor")
.AddItem(item => item
.AsScreenItem()
.WithText("New report")
.WithScreen<ReportScreen>()
)
)
.Build();
Sphere10Framework.Instance
.BuildWinFormsApplication()
.UseMainForm<BlockMainForm>(form => form.ScreenMode = ScreenMode.MultiView)
.AddServices(services => services.AddApplicationBlock(block))
.StartWinFormsApplication();
public class DashboardScreen : ApplicationScreen {
}
public class EditorScreen : ApplicationScreen {
}
public class ReportScreen : ApplicationScreen {
}
Screen registration builders declare each definition's instance policy with .AsSingleInstance() or .AsMultiInstance(). SingleInstance reuses one instance of that exact registration in its owning block, including its detached window. Another registration of the same CLR type can have a different title, activator, lifetime and screen kind. MultiInstance opens an independent instance on each activation. Set the policy on AddScreen, then attach any number of menu commands to that registration. A screen constructor supplies the fallback when the registration omits a mode; a hosted instance cannot change its resolved mode. The former KeepAlive and AlwaysCreate names are SingleInstance and MultiInstance.
ApplicationScreen.Title uses the control's Text property. The screen registration supplies its initial title; a command can have a different navigation caption. Screens can subsequently change Title; the tab and detached window update immediately. A block's default screen opens during registration if there is no active screen after its ExecuteOnLoad items have run.
Tab widths grow with their titles up to ApplicationScreenTabControl.MaximumTabWidth, which defaults to 320 logical pixels. Native caption measurements reserve room for the owner-drawn icon, its spacing and the close action, including when the image list retains its original pixel size on a higher-DPI monitor. Longer titles display an ellipsis, with the full title available on hover. Tab spacing, close buttons, docking markers, and the width limit scale for the current monitor's DPI.
Selecting a tab restores the previous screen's command views, then borrows the selected screen's ScreenMenuStrip and ScreenToolBar items into the main form. The same native items, handlers, state and images are retained. Matching headings combine actual native children, and leaving the screen restores their exact source ownership and order. Detached hosting preserves those commands and their native callbacks; redocking selects the returned tab and merges its items back into the main form. The legacy registered MenuItems path remains supported.
The application toolbar has one frame-owned row height. MainForm.ToolBarRowHeight defaults to 32 logical pixels at the standard menu font and scales for global font and DPI changes; switching between empty, ordinary and logging toolbars does not resize it. Configure a larger common row explicitly when an application supplies larger hosted controls. ToolStripStableHeightBehavior.LogicalHeight supplies this fixed-row mode independently of the current command set.
A screen's own toolbar, including in a detached window, uses the behavior's content-sized mode (LogicalHeight = 0). It reserves the preferred height of every current command, including temporarily hidden commands, so Live/paused visibility changes keep content in place. This mode uses preferred or explicit item sizes, margins, padding, fonts and current DPI; removing a tall control releases its height. Explicit caller minimum sizes are retained. Ordinary standalone strips can own the behavior; disposal restores the declared minimum and automatic sizing without disposing the borrowed strip.
Detached windows use a compact caption with accessible Re-dock, Minimize, Maximize/Restore, and Close icon buttons. The title area supports native dragging and double-click maximize/restore, and the border remains resizable. Close and re-dock preserve the screen's cancellation checks. Only menus and toolbars supplied by the screen occupy space; a content-only screen starts immediately below the caption, without empty bars or a detached tab row.
- Close a tab with its close button, middle-click, or its context menu. Closing the active tab selects the next surviving tab in visual order, otherwise the nearest previous tab. Closing the last tab leaves no active selection; an Empty screen remains available through normal startup/navigation rather than activating as a side effect of close. Closing inactive tabs preserves the current screen.
- Undock using the tab context menu, or drag the selected tab away from the tab headers and release. The dragged tab turns grey while release would request undocking, and returns to its normal appearance when moved back over the headers. Release, Escape, capture loss and tab removal clear that preview; permanent tabs never show an undocking hint.
- Drag tabs along the tab bar to see them move immediately; Escape restores the original position.
- In a detached window, use the caption's Re-dock icon, or bring the window's title bar close to the main tab strip. Only the header band accepts drag docking; the screen content panel does not. A highlighted tab-sized Release to dock preview and text hint show the proposed position and screen title without changing tab widths, order, or selection. The highlight uses the ExplorerBar palette and follows the visible navigation pane's blue in
BlockMainForm. Leaving the target or cancelling the drag clears the preview.
The left navigation pane starts at 320 logical pixels wide and scales with DPI. Drag its divider to choose a different width. MaximumNavigationPaneWidth defaults to 480 logical pixels at 96 DPI. Main-frame resizing changes the content pane's width, preserving the navigation width while the native panels physically fit. A physically unavoidable clamp does not replace NavigationPaneWidth: widening restores the preferred width without another divider move. Limits scale with DPI and clamp oversized saved preferences against the configured maximum. Minimized or temporarily undersized layouts defer divider updates until both panels fit; the remembered width remains available for restoration and settings capture. Collapse and restore the entire left navigation pane with the sidebar icon in the main toolbar, or Ctrl+Alt+M. The icon remains available across screen switches and supplies Show/Hide sidebar tooltips. It does not reserve a separate header or collapsed gutter. BlockMainForm.NavigationPaneCollapsed exposes the preference. The pane remembers its width and collapsed state across screen switches. Filled screens temporarily hide navigation without changing that preference.
Menu rows wrap captions to the available navigation width. Narrowing the pane increases row and group heights; widening it removes unnecessary wrapped lines. The navigation container keeps its menu viewport sized to the pane, including applications with one block and no block-selector buttons. Following groups move below their contents, with vertical scrolling when necessary.
MainForm.ScreenHost exposes ActivateScreen, ShowScreen, CloseScreen, CloseScreens, CanCloseScreens, UndockScreen, DockScreen, OpenScreens and Screens. ActiveScreen identifies the selected docked screen; detached windows retain independent chrome. Screens also includes cached single-instance screens hidden in SingleView. ActivateScreen and menu navigation reuse an existing singleton. Direct ShowScreen calls reject a second singleton instance; the caller still owns a rejected instance. A screen belongs to one host at a time.
LoadedPlugins, Blocks, Menus, Items, IBlockManager.RegisteredBlocks, Screens and OpenScreens expose arrays. The built-in models, application, block manager and screen host return snapshots: replacing entries in a returned array does not change their owned collections. Use menu mutation methods, block registration methods and screen-host operations to change those collections. The referenced plugins, blocks, menus and screens retain their existing identity and disposal ownership.
SingleView retains hidden single-instance screens and disposes multi-instance screens when navigating away, preserving the previous behavior. Explicit close destroys an ordinary instance; opening it again constructs a fresh screen. Switching from MultiView to SingleView closes other ordinary open screens and retains the selected screen. Permanent singletons remain owned and return to the tab strip when MultiView is restored. Use ScreenHost.TrySetScreenMode to handle cancellation without an exception; assigning ScreenMode throws if a screen vetoes the change.
ScreenActivationMode.PermanentSingleton adds an anchored lifetime. Declare it with .AsPermanentSingleton() in the block's AddScreen callback. These registered permanent screens are created once at startup, remain in OpenScreens across both view modes, and reject close and undock requests. Ordinary navigation away remains allowed. Declare the policy in registration when it must open automatically; a constructor-only default is learned when that type is first activated.
ScreenKind.Empty marks a tabless fallback shown only when no regular screen remains open (detached windows and permanent screens also count as open). It is excluded from OpenScreens, while Screens includes a cached Empty singleton. Navigating away retains a singleton's controls and disposes a multi-instance placeholder; returning either reuses or recreates it. Empty and PermanentSingleton cannot be combined.
using Sphere10.Framework.Application.UI;
using Sphere10.Framework.Windows.Forms;
var block = new ApplicationBlockBuilder()
.WithName("Workspace")
.AddScreen<StartScreen>(screen => screen
.WithTitle("Start")
.AsSingleInstance()
)
.AddScreen<NotesScreen>(screen => screen
.WithTitle("Pinned notes")
.AsPermanentSingleton()
)
.WithDefaultScreen<StartScreen>()
.AddMenu(menu => menu
.WithText("Screens")
.AddShowScreenItem<StartScreen>("Start")
.AddShowScreenItem<NotesScreen>("Pinned notes")
)
.Build();
var emptyBlock = new ApplicationBlockBuilder()
.WithName("Empty workspace")
.AddScreen<EmptyScreen>(screen => screen
.WithTitle("Nothing open")
.AsSingleInstance()
.WithScreenKind(ScreenKind.Empty)
)
.WithDefaultScreen<EmptyScreen>()
.Build();
The screen types in this example derive from ApplicationScreen. Startup selects the first configured block WithDefaultScreen in plugin and block declaration order. A permanent screen prevents an Empty default from taking selection. Block Position continues to order the displayed navigation independently. If no explicit default exists, existing IsStartScreen / ExecuteOnLoad screen registrations keep their behavior; startup actions still execute.
The tab context menu's Make Startup Screen saves an
ApplicationStartupScreenSettings preference through the application's
UserSettings. The host loads it asynchronously before block registration and
prefers a matching registered screen over the configured default, while still
creating permanent screens. Identity uses the owning plugin/block and stable screen registration key;
captions, menu order, assembly versions and live session handles are not persisted.
A legacy type-only preference restores only when that type identifies one
registration in the owning block. Missing, invalid or non-restorable definitions fall back to
the configured default without overwriting the preference. Override
ApplicationScreen.CanRestoreAtStartup to false for screens that require
session arguments; their context action remains visible with an explanation.
BlockMainForm.RegisterBlock initializes new permanent screens without replacing an ordinary active screen. If an active Empty screen refuses the transition, the new block remains unregistered and undisposed so the caller can retry after clearing the guard. For a standalone host, InitializeScreens(blocks) returns whether initialization was accepted. UnregisterScreenTypes(block) removes its definitions and owned screens after all close guards agree. The form's existing UnregisterBlock uses that path, allowing administrative removal of permanent screens and disposal of hidden Empty instances. CanCloseScreens(Screens) remains the application-exit guard: permanent lifetime does not prevent shutdown.
The main window's status bar shows IUserInterfaceServices.LoadingIndicator: a loading circle and its message while any scope returned by LoadingIndicator.Show(message) lasts, from any thread. The screen host shows it while it creates a screen ("Opening …") and while it closes screens ("Closing …"), entered before the transition suspends drawing so it paints first. A screen that works in the background shows what it is doing the same way.
Each screen change runs inside one rendering scope over the window, so the change paints once. Work a screen starts asynchronously after it is shown (such as reading and binding its tables) paints when it completes; VisualGrid binds a page and settles its geometry under one paint. Do not keep a rendering scope across message processing to wait for that work: suppressed redraw removes a window's native visibility, so its controls can neither be clicked nor take focus meanwhile, and a top-level window would pass clicks to the window behind it.
The existing OnHide(ref bool CancelHide) and ScreenHidden event can cancel navigation, close, undock, redock, block removal, and changes to SingleView. Batch close and mode changes check all affected screens before removing any. ScreenDisplayedFirstTime runs once per instance; ScreenDisplayed runs on each subsequent selection or hosting transition. Closing or disposing the host also disposes hidden and detached instances, with ScreenDestroyed raised once per instance.
The reusable host follows IApplicationScreenHost → ApplicationScreenHostBase → ApplicationScreenHost, with ApplicationScreenHostDecorator for extensions. ApplicationScreenTabControl supplies the tab interactions and ApplicationScreenForm hosts detached screens.
MainForm and BlockMainForm provide a Screens menu listing the exact open instances across blocks, including detached windows. Duplicate titles receive an occurrence number; detached entries are marked Undocked. Selecting an entry navigates to that instance without opening another or docking its window. The menu and tab context menus expose Close All and Close All Others. CloseAllScreensAsync and CloseAllOtherScreensAsync(keepScreen) close docked and detached instances through the existing atomic guard checks; permanent screens remain open. Hidden retained singletons are not open menu entries, and the ordinary exit guard still includes them.
The WinForms Tester loads two plugins through AddWinFormsApplicationPlugin: WinFormsDemoPlugin.Configure contributes Workspace and Notes, while WinFormsComponentDemoPlugin.Configure contributes Controls, Data and collections, Integration, and Utilities. Each plugin registers its own initialization and finalization tasks from the tester's Lifecycle folder, alongside the existing framework startup tasks. It starts in MultiView and uses HighDpiMode.DpiUnaware so Windows bitmap-scales its existing screen and dialog layouts. Workspace > Screen hosting explicitly declares Settings as single-instance; New design and ordinary component screens use the multi-instance default. Both screen modes are available, and the hidden Empty screen belongs to Workspace. These demos have independent notes, a counter, Rename tab actions, a lifecycle log, and a checkbox to exercise cancellation. Plain screen (no bars) exercises a screen with no menus or toolbar. See the Tester instructions. SystemExpert is an independent diagnostic application consuming these hosts and the Windows diagnostics library; the framework checkout does not require its source or tests.
Directory.Build.props sets ForceDesignerDPIUnaware=true for the Visual Studio WinForms designer across the repository. This designer setting is separate from runtime DPI awareness. The library leaves runtime DPI policy to the application; Tester explicitly selects HighDpiMode.DpiUnaware before creating controls to preserve Windows bitmap scaling.
For a stable main-window layout in an otherwise per-monitor-aware process, select
UseMainForm<MainForm>(DpiAwarenessContext.SystemAware). Windows scales this
window between monitors instead of relaying DPI changes to its layout. Text can
look softer away from the system DPI. The overload applies the context during
construction and restores the caller's context. The existing overload inherits
the caller's awareness. Construct independent per-monitor overlays inside
using (Tools.Scope.EnterThreadDpiAwarenessScope(DpiAwarenessContext.PerMonitorAwareV2)) { ... }
and scope operations that use physical desktop coordinates the same way. Import
Sphere10.Framework.Windows for the enum and Tools for the scope factory.
Global keyboard shortcuts
GlobalHotKey implements IGlobalHotKey using a private message-only window and
the Windows hotkey API, independently of low-level keyboard hooks. Create,
register, unregister and dispose it on the same UI thread. Construction performs
no registration; TryRegister(Keys.Control | Keys.Alt | Keys.A, out error) begins
receiving Pressed events through the native message loop. Keys.None disables
the shortcut. Windows auto-repeat is suppressed, so holding the key does not
toggle repeatedly.
An unavailable shortcut returns an error while retaining its previous active
registration. Modifier-only keys, F12 and unsupported combinations are rejected.
Keys has no Windows-key modifier, so combine GlobalHotKey.WindowsKey with the
key and the ordinary Keys modifiers (GlobalHotKey.WindowsKey | Keys.Alt | Keys.L);
it maps to MOD_WIN on registration.
Disposal unregisters the shortcut and destroys the owned window. The consuming
application owns its activation policy, settings, user feedback and subscription
lifetime; keep registration alive when temporarily disabling the operation it
controls. AutoMouse and Lumina use this component for their configurable shortcuts.
HotKeyEditor is the matching designer-editable
UserControlEx: Win, Ctrl, Alt and Shift check boxes plus an EnumComboBox of the keys
GlobalHotKey accepts (HotKeyEditor.IsEditableKey). Read or assign Shortcut
(Keys.None for no shortcut) and observe ShortcutChanged or the inherited
StateChanged; HotKeyEditor.Describe(shortcut) formats "Ctrl+Alt+L" captions.
Configurable shortcut commands
An application's configurable shortcuts are three pieces, and the application keeps only its commands and where it stores the assignments:
- HotKeyCommand
(name, caption, defaultShortcut, execute) { Group }describes one operation a user can bind; the name is the stable identifier stored in settings. - HotKeyAssignment is the serializable user choice
(
Command,Shortcut) kept in a settings object. Only choices that differ from a command's default are stored, so a changed default reaches users who never changed it, andKeys.Nonerecords a removed default.Resolvegives the shortcut in force,Assignreturns updated assignments, andFindConflictslists commands sharing a shortcut. - GlobalHotKeySet keeps them registered:
Apply(commands, assignments)after every settings change. Bindings are matched by name, ignoring case: a changed shortcut re-registers, an unchanged one keeps its registration and takes the new action, and a removed command orKeys.Nonereleases its hot key. A failed change keeps the previous registration;ErrorsByKey(andErrors) report "Caption (Win+Alt+K): reason" from the latest apply, and a new binding that failed holds no hot key, so the next apply retries it. Exceptions from actions are ignored. OverrideCreateHotKeyto supply anotherIGlobalHotKey, for example in tests.Apply(GlobalHotKeyBinding[])registers ad hoc bindings without the command model.
HotKeyCommandEditor is the options-screen
control: a list of the commands by Group with Shortcut and Status columns, and a
HotKeyEditor with Clear and Default for the selected command. Edits apply at once
and raise AssignmentsChanged; the status column marks conflicts and the errors passed
to ShowRegistrationErrors. Use the set and editor on the UI thread.
// Commands, built once from the application's operations.
var commands = new[] {
new HotKeyCommand("Toggle", "Turn on or off", GlobalHotKey.WindowsKey | Keys.Alt | Keys.L, engine.Toggle) { Group = "General" },
new HotKeyCommand("Next", "Next effect", GlobalHotKey.WindowsKey | Keys.Alt | Keys.K, engine.NextEffect) { Group = "General" }
};
// Options screen: edit and save.
editor.Commands = commands;
editor.Assignments = settings.Shortcuts;
editor.AssignmentsChanged += (_, _) => { settings.Shortcuts = editor.Assignments; settings.Save(); };
// Main window: register after every save and report back.
_hotKeys ??= new GlobalHotKeySet();
_hotKeys.Apply(commands, settings.Shortcuts);
editor.ShowRegistrationErrors(_hotKeys.ErrorsByKey);
Tool strip images
ToolStripItem.ReplaceImage(image) sets an image the caller owns and disposes the one
it replaces. ReplaceImage(icon, pixelSize) renders an icon at a pixel size (pass
form.LogicalToDeviceUnits(16)), scaling the icon's closest frame. WinForms keeps
tool strip images at the size they were created for, so call it again from the form's
OnDpiChanged.
On-screen notifications
OnScreenNotificationForm is a
passive, topmost, click-through popup that confirms a state change without taking
focus, in the style of "AUTOMOUSE ON". ShowMessage(text) places it centered
near the bottom of the screen under the pointer (ShowMessage(text, screen)
selects a screen), replaces any current text and restarts the dismissal timer
(DisplayDurationMilliseconds, default 1500; BottomMargin in logical pixels).
The form autosizes to its text; wording, triggers and whether labels are shown at
all remain application policy. For one-off labels, such as a number on every screen
like Identify in the Windows display settings, OnScreenNotificationForm.ShowTransient(text, screen, durationMilliseconds)
shows a popup of its own that disposes itself once dismissed.
Monitor layout
MonitorLayoutControl draws the desktop's
display arrangement as proportional, selectable tiles in the style of Windows
display settings. Supply Items as MonitorLayoutItem
values (key, large label, caption, physical Bounds, primary flag, enabled flag
and accent color); the control owns scaling, hover, the selection ring and
SelectedItemChanged/SelectedKey, and HitTest resolves a client point. The
application decides what a tile's caption and accent mean, such as the effect
applied to that display.
The layout can also host controls. With HostedControlMode = PerTile, each control
given to SetTileControl(key, control) sits centred beneath its tile; a display that
lies below another is moved down so no hosted control covers a tile. With Shared,
SharedControl sits centred beneath the whole arrangement, sized within its
MinimumSize and MaximumSize. HostedControlSpacing (4 logical pixels) separates
a tile from its control and SharedControlSpacing (12) the arrangement from the shared
one. None keeps the plain layout. GetPreferredSize(width) returns the height that
shows the arrangement at that full width with its hosted controls and no empty band. It
reserves the larger of the two modes' bands, so a fixed-size window can fit itself to
the desktop's arrangement and keep its size when the mode changes. The tiles are laid out
with that same reservation, so they keep their scale and position when the mode changes
and only the hosted controls swap. The layout owns the
hosted controls' bounds, visibility (only the current mode's controls, and only for
keys still in Items) and tab order; SetTileControl(key, null) hands a control back
without disposing it, and GetTileBounds returns a tile's rectangle. An application can, for example,
put a picker beneath each display in one mode and one shared picker in another.
Switches and image choices
ToggleSwitch is a CheckBox drawn as a thumb sliding in
a rounded track, so Checked, CheckedChanged, AutoCheck, Space toggling, data
binding and accessibility behave as for a check box. OnText and OffText are drawn
inside the track, OnBackColor, OffBackColor, ThumbColor and TrackForeColor
colour it, and AnimateToggle slides the thumb. A transparent BackColor shows the
parent (for example a GradientPanel banner), and a switch sized explicitly larger
than its preferred size grows its track to the height. Set AutoCheck to false when
the application's state, not the click, decides the position, and set Checked from
that state.
CloseOrExitButton is the Close button of a window that
hides to the tray. Its main part raises Click, which the window handles by hiding, and
the arrow, a right-click, Down or the Applications key open its own drop-down with
Exit Application (ExitText), which raises ExitApplicationClick for the window to
exit, as its tray menu's Exit does:
_closeButton.Click += (_, _) => Hide();
_closeButton.ExitApplicationClick += (_, _) => Exit();
It derives from SplitButton, whose drop-down section and arrow
follow the control's DPI and whose divider is always drawn. The button owns and disposes
its menu; ExitMenuItem exposes the item for an image or tool tip, and neither the menu
nor ContextMenuStrip is serialized by the designer.
CaptionedRadioButton is a RadioButton whose
text is a bold Caption, a CaptionSeparator (": ") and a regular Description,
such as "Per Display: unique effect per display (slower)". Grouping, arrow keys,
CheckedChanged and accessibility stay RadioButton behaviour; Text follows the
three parts for screen readers. RadioButton itself paints the background and the
standard glyph, with its hot and pressed states, at the window's own DPI; the control
draws only the text and focus rectangle. With AutoSize its height is a standard radio
button's, so stacked buttons with default margins keep the designer's snap-line spacing.
ImageComboBox is a CustomComboBox of
ImageComboBoxItem choices (text, image, value, tool
tip, optional group). The closed box draws the selected choice's image at ImageSize
and its text; the drop-down is an owned tile picker showing every choice at
TileImageSize, grouped by Group, sized for TileColumns by VisibleTileRows. A
click or Enter on a tile picks it, closes the drop-down and raises
SelectedChoiceCommitted, as do keyboard changes in the closed box; SelectedChoice
and SetChoices in code raise nothing. Images are borrowed: render them at
DeviceTileImageSize, dispose them after replacing the choices, and keep one set for
several combos. The picker always uses the combo's font, because the popup rescales
its content again when it opens on a display with another DPI.
📦 Dependencies
- Sphere10.Framework: Core framework
- Sphere10.Framework.Data: Database abstraction
- System.Windows.Forms: Windows Forms (.NET built-in)
- System.Drawing: Graphics support
📖 Related Projects
- Sphere10.Framework.Windows.Forms.Sqlite - SQLite connection panel
- Sphere10.Framework.Windows.Forms.MSSQL - SQL Server connection panel
- Sphere10.Framework.Windows.Forms.Firebird - Firebird connection panel
- Sphere10.Framework.Windows - Windows platform integration
- Sphere10.Framework.Data - Database abstraction layer
✅ Status & Compatibility
- Maturity: Production-tested for Windows desktop applications
- .NET Targets:
net10.0-windows, plusnet11.0-windowswhen built with a .NET 11 SDK. The library builds on .NET 10 Windows Forms APIs such asForm.ShowDialogAsync, which itsIApplicationDialogdialogs use, so it has no .NET 8 or 9 build; the non-UISphere10.Framework.Windowsand core packages it uses also target .NET 8 and 9 - Platform: Windows only (Windows Forms)
⚖️ License
Distributed under the MIT License.
See the LICENSE file for full details. More information: MIT License
👤 Author
Herman Schoenfeld - Software Engineer
Native helper migration
Reusable native interop now lives in Sphere10.Framework.Windows, accessed through WinAPI and Tools.Windows.Win32. Windows Forms retains control lifecycle, message dispatch, and wrappers such as Tools.WinForms.CreateCursor. Sound playback moved to Sphere10.Framework.Windows.SoundPlayerEx.
Code using the former low-level APIs should update these references:
Tools.WinForms.IconInfo,CreateIconIndirect, andGetIconInfomoved toWinAPI.USER32.ICONINFO,WinAPI.USER32.CreateIconIndirect, andWinAPI.USER32.GetIconInfo.DevAgeRichTextBox's native constants and protectedCHARFORMATmoved toWinAPI.RICHEDIT; derived controls should passWinAPI.RICHEDIT.CHARFORMATtoSetCharFormatMessage.- Popup/combo-box native constants moved to
WinAPI.USER32; word extraction helpers moved toTools.Windows.Win32. Native sizing/tab structures now useWinAPI.USER32.MINMAXINFOandWinAPI.COMCTL32.TCITEM.
These low-level moves require recompilation and the listed source updates for consumers of the moved members. Rich-edit formatting, cursor hotspots, native struct sizes, and hook disposal have regression coverage in WindowsInteropTests. The cursor wrapper does not transfer native-handle ownership to Cursor.Dispose; direct native consumers should use CreateCursorHandle and release their handle explicitly.
Ordinary custom forms can override OnFormClosing(FormClosingEventArgs). LiteMainForm seals that workflow to coordinate IApplication.ExitAsync; application forms can veto normal exit through OnApplicationExiting(CancelEventArgs) or ApplicationExitingEvent. Image attachment selection returns the selected file or clipboard source instead of always reporting None.
Legacy DES stream helpers retain their existing full-length input buffer and zero-filled tail at end of input; short reads are completed before encryption or decryption. The existing DES key, IV, and ciphertext format are preserved.
Native application and block descriptor commands compose inside the framework presentation adapter. Application commands survive contextual commands with the same caption. Screens contribute their actual ScreenMenuStrip and ScreenToolBar commands; the native host transfers and restores those same item instances as screens are selected or detached. Native captions merge without mnemonic markers, including contributions to the existing File and Help headers. Exit and help commands survive screen changes, with Help last. Native presentation honors block/menu placement flags and preserves caller-owned menu and item references.
Control.EnterRenderingScope() defers layout and native redraw across the control tree. Nested scopes, added controls, newly created handles and newly shown controls share suppression. The last scope flushes parent/child layout and performs one redraw; disposed and intentionally hidden controls remain so. Controls moved into another window receive their final full-tree invalidation at their current surviving root, including when the original root was disposed. A subtree still held by another rendering scope waits for that owner to release it. EnterRenderingScope(repaintImmediately: false) restores layout and native visibility synchronously but queues painting for the next normal native paint cycle, appropriate inside native input/selection callbacks. The existing no-argument overload retains immediate painting. Dispose scopes on the creating UI thread; never keep one across an await or BeginInvoke. Screen-host transitions use this scope around the form and publish one completed selection and command update.
Native redraw suppression temporarily removes WS_VISIBLE; old pixels can remain while Windows routes mouse input to another window. An enabled control and a responsive managed message loop do not establish that its native input target remains available. Live VisualGrid publication and incremental native sizing therefore use SourceGrid's existing double buffering and managed layout suspension, without WM_SETREDRAW. A single-row publication explicitly invalidates the changed view, including when no row is selected. Native input regressions sample cached HWND visibility and hit-test routing from a worker during publication, rather than calling control handlers directly or observing only UI timer ticks.
After native resizing and redraw restoration, the scope compares a top-aligned TabControl's native TCM_ADJUSTRECT display area with WinForms' cached display rectangle. During toolbar restoration and undocking, managed OnResize can run before the native WM_SIZE recalculates wrapped header rows; the retained page then covers those headers. A mismatch reapplies the selected page's existing nonvirtual image metadata, whose parent update clears that cache. Its image-key/index mode, captions, custom text setters, native handles, selected page and selection events remain unchanged. This synchronization finishes before the existing final invalidation; it does not resize or recreate controls or select another page.
SourceGrid controller dispatch uses a cached membership snapshot. Controllers may add or remove controllers while handling a mouse, keyboard, focus or editing callback; the current event retains its admitted order and nested/subsequent events use the updated membership. A new snapshot is allocated only when membership changes.
Restoring redraw preserves each control's own requested visibility, rather than its effective Visible value inherited from a hidden parent. The base Control.Visible designer descriptor supplies that state through ShouldSerializeValue, even when a derived control declares a different default. Native regression checks must inspect actual window visibility after hiding and reactivating a retained view: healthy managed bounds alone do not prove its dropdowns and search controls are painted.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0-windows7.0 is compatible. net11.0-windows7.0 is compatible. |
-
net10.0-windows7.0
- Sphere10.Framework (>= 3.2.0)
- Sphere10.Framework.Application (>= 3.2.0)
- Sphere10.Framework.Data (>= 3.2.0)
- Sphere10.Framework.Drawing (>= 3.2.0)
- Sphere10.Framework.Windows (>= 3.2.0)
- Sphere10.Framework.Windows.Forms.DataVisualization (>= 3.2.0)
-
net11.0-windows7.0
- Sphere10.Framework (>= 3.2.0)
- Sphere10.Framework.Application (>= 3.2.0)
- Sphere10.Framework.Data (>= 3.2.0)
- Sphere10.Framework.Drawing (>= 3.2.0)
- Sphere10.Framework.Windows (>= 3.2.0)
- Sphere10.Framework.Windows.Forms.DataVisualization (>= 3.2.0)
NuGet packages (6)
Showing the top 5 NuGet packages that depend on Sphere10.Framework.Windows.Forms:
| Package | Downloads |
|---|---|
|
Sphere10.Framework.Windows.Forms.Sqlite
Windows Forms integration for Sphere10.Framework.Data.Sqlite. Provides desktop UI helpers and components intended to work with Sphere10 Framework WinForms and the SQLite provider for data-driven applications. |
|
|
Sphere10.Framework.Windows.Forms.Firebird
Windows Forms integration for Sphere10.Framework.Data.Firebird. Provides desktop UI helpers and components intended to work with Sphere10 Framework WinForms and the Firebird provider for data-driven applications. |
|
|
Sphere10.Framework.Windows.Forms.MSSQL
Windows Forms integration for Sphere10.Framework.Data.MSSQL. Provides desktop UI helpers and components intended to work with Sphere10 Framework WinForms and the SQL Server provider for data-driven applications. |
|
|
Sphere10.Framework.Windows.Forms.Oracle
Windows Forms integration for Sphere10.Framework.Data.Oracle. Provides desktop UI helpers and components intended to work with Sphere10 Framework WinForms and the Oracle provider for data-driven applications. |
|
|
Sphere10.Framework.Windows.Forms.MySQL
Windows Forms integration for Sphere10.Framework.Data.MySQL. Provides desktop UI helpers and components intended to work with Sphere10 Framework WinForms and the MySQL provider for data-driven applications. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 3.2.0 | 0 | 11/24/2026 |
| 3.2.0-ci.173.45375449609.1 | 0 | 11/24/2026 |
| 3.2.0-ci.171.45374063975.1 | 0 | 11/24/2026 |
| 3.2.0-ci.169.45350717665.1 | 0 | 11/24/2026 |
| 3.2.0-ci.168.45166918016.1 | 47 | 11/23/2026 |
| 3.2.0-ci.163.43664782937.1 | 103 | 11/15/2026 |
| 3.2.0-ci.160.43660265392.1 | 95 | 11/15/2026 |
| 3.2.0-ci.159.43537748063.1 | 101 | 11/14/2026 |
| 3.2.0-ci.158.43536665157.1 | 98 | 11/14/2026 |
| 3.2.0-ci.157.43350632870.1 | 102 | 11/13/2026 |
| 3.2.0-ci.156.43233095581.1 | 96 | 11/12/2026 |
| 3.1.2 | 196 | 9/9/2026 |
| 3.1.1 | 168 | 9/8/2026 |
| 3.1.0 | 151 | 9/7/2026 |
| 3.0.3 | 193 | 1/6/2026 |
| 3.0.2 | 166 | 1/2/2026 |
| 3.0.1 | 160 | 1/2/2026 |
| 3.0.0 | 164 | 1/2/2026 |