From cb8e6bbba29936182c2046e0e5f386653d204549 Mon Sep 17 00:00:00 2001 From: Klaus Loeffelmann Date: Sat, 18 Jul 2026 01:26:39 -0700 Subject: [PATCH 01/69] Centralize feature prompt documents Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 27022e2a-9eb8-4f58-9bfa-e79ca0d6c559 --- ...B05-HighPrecisionTimer-Rework-WorkOrder.md | 157 +++++++++++++++ ...B01-SystemVisualSettings-Implementation.md | 158 +++++++++++++++ ...sualStylesMode-ImpactApi-Implementation.md | 137 +++++++++++++ .../Application.SystemTextAwareness.md | 180 ++++++++++++++++++ .../TextBoxBase-VisualStyles-WorkOrder.md | 137 +++++++++++++ .../Create-Github-API-Proposal-Prompt.md | 120 ++++++++++++ ...elocationAndPainting-API-Feature-Prompt.md | 76 ++++++++ .../invokeAsync_generate_test_instructions.md | 0 ...uttonRendererCodeGenerationInstructions.md | 0 9 files changed, 965 insertions(+) create mode 100644 .github/Feature-Prompts/Net11/01-B05-HighPrecisionTimer-Rework-WorkOrder.md create mode 100644 .github/Feature-Prompts/Net11/02-B01-SystemVisualSettings-Implementation.md create mode 100644 .github/Feature-Prompts/Net11/03-B05-VisualStylesMode-ImpactApi-Implementation.md create mode 100644 .github/Feature-Prompts/Net11/Application.SystemTextAwareness/Application.SystemTextAwareness.md create mode 100644 .github/Feature-Prompts/Net11/Application/net11-VisualStylesMode/TextBoxBase-VisualStyles-WorkOrder.md create mode 100644 .github/Feature-Prompts/Net11/SuspendRelocationPaintingFlashPreventing/Create-Github-API-Proposal-Prompt.md create mode 100644 .github/Feature-Prompts/Net11/SuspendRelocationPaintingFlashPreventing/SuspendRelocationAndPainting-API-Feature-Prompt.md rename .github/{copilot => Feature-Prompts/Net9}/Async/invokeAsync_generate_test_instructions.md (100%) rename .github/{copilot => Feature-Prompts/Net9}/GDI/DarkModeButtonRendererCodeGenerationInstructions.md (100%) diff --git a/.github/Feature-Prompts/Net11/01-B05-HighPrecisionTimer-Rework-WorkOrder.md b/.github/Feature-Prompts/Net11/01-B05-HighPrecisionTimer-Rework-WorkOrder.md new file mode 100644 index 00000000000..470d3584b5b --- /dev/null +++ b/.github/Feature-Prompts/Net11/01-B05-HighPrecisionTimer-Rework-WorkOrder.md @@ -0,0 +1,157 @@ +# Work Order: HighPrecisionTimer Rework (Animation Timing) + +**Branch:** `Net11/Integration-2` (KlausLoeffelmann/winforms) +**Files:** +- `src/System.Windows.Forms.Primitives/src/System/Windows/Forms/Animation/HighPrecisionTimer.cs` +- `src/System.Windows.Forms.Primitives/src/System/Windows/Forms/Animation/HighPrecisionTimerTick.cs` +- `src/System.Windows.Forms.Primitives/tests/UnitTests/System/Windows/Forms/Animation/HighPrecisionTimerTests.cs` +- Consumer: `src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationManager.cs` + +This work order is self-contained; it results from a code review of the current implementation. +Read the current sources first, verify each finding against the code as it stands (the branch may have +moved), then implement. + +**Keep as-is (explicitly not up for redesign):** the registration model — per-registration +`SynchronizationContext` capture, `InFlight` CAS-based frame coalescing with a `DroppedFrames` counter +surfaced in `HighPrecisionTimerTick`, and the id-based `TimerRegistration` disposable struct +(double-dispose safe, `default` safe). The *clock/pacing core* is what gets replaced. + +--- + +## Finding 1 (critical): fixed-cadence pacer + spin causes a sawtooth burning ~50% of a core + +Current design: `PeriodicTimer` at 14 ms (60 Hz path), then `SpinToTarget` spins to the 16.667 ms +frame target with `SpinOnce(sleep1Threshold: -1)` (never sleeps). + +`PeriodicTimer` fires on its own **fixed** cadence (14, 28, 42, 56, …) and does not re-phase per +`WaitForNextTickAsync` call, while frame targets are 16.67, 33.33, 50, 66.67, … The phase slips +2.67 ms per frame, so spin duration grows every frame — wake 28 → spin 5.3 ms; wake 42 → spin 8 ms; +wake 56 → spin 10.7 ms — until phases wrap and the sawtooth restarts. Average spin ≈ half a frame +≈ 8 ms of every 16.67 ms ⇒ ~50% of one core, continuously, for as long as **any** animation is +registered. Infinite cycles (e.g. a pulsing focus indicator) make this permanent. The 30 Hz path +(30 ms tick vs 33.33 ms frame) has the identical slip. + +**Required fix (architecture, not constant-tuning):** absolute schedule. Due times are +`epoch + frameIndex * period` against a single clock; wait on a mechanism that can hit them +(Finding 3), with at most a sub-millisecond residual spin. Overshoot must be amortized against the +absolute schedule (no `lastTick + period` relative scheduling — that accumulates and runs slow). + +## Finding 2: integer-millisecond arithmetic throughout + +`stopwatch.ElapsedMilliseconds` (truncated `long`) feeds `lastTickTimestamp`, `elapsed`, the spin +target, drift detection, and the `Timestamp`/`Elapsed` values delivered to consumers — ±1 ms +quantization (6% of a 16.667 ms budget) plus systematic truncation bias. Use `ElapsedTicks` / +`Elapsed.TotalMilliseconds` (double) end to end; `HighPrecisionTimerTick` fields stay `TimeSpan`, +constructed from ticks. + +## Finding 3: replace `timeBeginPeriod(1)` with a high-resolution waitable timer + +The code gates on `windows10.0.17134` — which `timeBeginPeriod` (ancient) does not need, but which is +exactly the build (1803) that introduced `CreateWaitableTimerExW` with +`CREATE_WAITABLE_TIMER_HIGH_RESOLUTION`. Use it: + +- absolute due times (negative-relative or absolute FILETIME) with sub-ms accuracy, +- no process-wide timer-resolution raise (current code holds 1 ms resolution for the entire lifetime + of any animation — a documented power/battery anti-pattern, and post-Win11 the effective resolution + changes for occluded windows, silently shifting the timing floor), +- composes directly with Finding 1's absolute schedule and eliminates the spin loop almost entirely. + +Fallback below 17134: keep a coarse path (30 Hz, plain waits, no `timeBeginPeriod`) — document that +sub-frame precision is not attempted there. Remove `TimeBeginPeriod`/`TimeEndPeriod` P/Invokes if no +longer referenced. + +## Finding 4: `Register`/`Unregister` vs `StopTimer` race strands registrations + +`Unregister` does `TryRemove` → `IsEmpty?` → `StopTimer()` without coordinating with `Register`. +Interleaving: A removes the last entry and observes empty; B adds a registration and `EnsureRunning` +sees `s_loopTask != null` (still running) and returns; A stops the timer. Result: live registration, +dead timer — animation frozen until an unrelated `Register` restarts the loop. +**Fix:** perform the emptiness check + stop decision under `s_lock` together with loop-state +transitions, or introduce a generation counter that `StopTimer` validates before actually stopping. + +## Finding 5: per-frame, per-registration closure allocations on the hot path + +`SyncContext.Post(_ => _ = InvokeCallbackAsync(registration, tick, cancellationToken), null)` +allocates closure + delegate per registration per frame (60 Hz × N renderers of steady GC pressure). +**Fix:** one cached `static SendOrPostCallback`; pass state via a per-registration state object — +`InFlight` guarantees exclusivity, so tick data can be written into a reusable per-registration slot +before posting. Target: zero allocations per frame in steady state. + +## Finding 6: drift `Debug.Assert` is an assert storm + +Drift >20% for 10 frames is normal under a debugger, breakpoints, or CI load. Once tripped, +`consecutiveDriftFrames` keeps incrementing, so the assert fires **every subsequent frame**. +**Fix:** replace with tracing/EventSource counters (drift, dropped frames, spin time). If any assert +remains, reset the counter after firing once. + +## Finding 7: lifecycle edges + +- `StopTimer` never observes `s_loopTask`; a stop/start pair can transiently run two loops, and a + stopping loop can dispatch one final frame with a canceled token. Decide and document: either join + the old loop (bounded) or make late dispatch provably benign. +- Post-unregister ticks can still be in flight toward a disposed consumer; `AnimationManager` / + `AnimatedControlRenderer` must tolerate late callbacks — add a test. +- `Reset()` (test hook) mutates state without locking — document the serialization requirement or + lock it. +- Dead code: `Registration.Id` is never read. +- `InvokeCallbackAsync` swallows non-OCE exceptions with `Debug.Fail` and keeps invoking the same + callback forever; consider auto-unregistering a registration after N consecutive faults. + +## Finding 8: single-SyncContext funnel in `AnimationManager` (design note) + +`HighPrecisionTimer` correctly captures a `SynchronizationContext` **per registration**, but +`AnimationManager` is a process-wide singleton with a single registration, so every animation in a +multi-message-loop application marshals to the first UI thread — and dies with it. Minimum: document +the constraint. Better: make the manager per-UI-thread (e.g. `[ThreadStatic]` instance keyed off the +message-loop thread), preserving one timer-registration-per-UI-thread. Also note the duplicate +timeline: the manager keeps its own `Stopwatch` instead of deriving progress from +`HighPrecisionTimerTick.Timestamp/Elapsed`; animation progress should use the tick's timeline so frame +coalescing (`DroppedFrames`) is accounted for consistently. + +## Finding 9: 60 Hz is a settled ceiling; the period is a pacer-owned runtime value for *downshift* + +**Decision (do not relitigate):** the timer targets a hard 60 Hz ceiling (30 Hz fallback). Do not +add refresh-rate matching or raise the cadence. Rationale, for the record: + +- Under DWM, windowed GDI/GDI+ apps do not tear (composition is tear-free from the redirection + surface); the only artifact of an unsynced 60 Hz timer is judder, which is imperceptible for this + content class (focus pulses, hover fades, toggle transitions — not motion/scrolling). +- GDI+ raster cost scales linearly with rate; driving N animated controls at 120–144 Hz multiplies + compute for no perceptible gain (e.g. batched MVVM-driven updates across many controls). +- A process-wide timer cannot refresh-match on mixed-rate multi-monitor setups ("the" refresh rate + is ill-defined), and `DwmFlush`-style vblank pacing blocks per frame, binds to one monitor, and + misbehaves under RDP — unfit for a process-wide UI timer by construction. + +**Required now (structural):** the frame period must be a runtime value owned by the pacer +(queryable/settable internally), not compile-time constants woven through the loop. The 30 Hz +fallback already makes the period variable; the forward-looking motivation is **downshifting**, not +matching: future power-driven reductions (30 Hz or full pause for occluded/minimized windows — where +Windows 11 timer coalescing already alters the effective cadence — and battery-saver scenarios) +must be addable without another rework. + +--- + +## Acceptance criteria + +1. Steady-state CPU of the timer loop with one registered infinite animation: **< 2% of one core** + (measure; the current implementation is the ~50% baseline per Finding 1). +2. No `timeBeginPeriod` while animations run (verify via `powercfg /energy` or timer-resolution + query on a Win10 1803+ box). +3. Frame delivery: mean interval within ±0.5 ms of target over a 10 s run on an idle machine at + 60 Hz; no monotonic slow drift (absolute-schedule check: 600th frame due time within one frame of + `epoch + 600 × period`). +4. Zero per-frame heap allocations in steady state (verify with an allocation-tracking test or + `GC.GetAllocatedBytesForCurrentThread` bracketing). +5. Race test for Finding 4: concurrent register/unregister stress leaves no registration without a + running loop. +6. Existing `HighPrecisionTimerTests` updated/extended accordingly; late-callback tolerance test for + consumers (Finding 7). +7. `HighPrecisionTimerTick` surface unchanged (internal consumers depend on it); all other churn is + internal to the pacer. + +## Constraints + +- Everything stays `internal`; no public API review implications. +- Follow repo conventions (`LibraryImport`, nullable enabled, existing XML-doc voice). +- Windows-only paths gated with `[SupportedOSPlatform]` / `OperatingSystem.IsWindowsVersionAtLeast` + as currently practiced in the file. diff --git a/.github/Feature-Prompts/Net11/02-B01-SystemVisualSettings-Implementation.md b/.github/Feature-Prompts/Net11/02-B01-SystemVisualSettings-Implementation.md new file mode 100644 index 00000000000..56070f96b3e --- /dev/null +++ b/.github/Feature-Prompts/Net11/02-B01-SystemVisualSettings-Implementation.md @@ -0,0 +1,158 @@ +# Work Order: SystemVisualSettings (Implementation) + +**Branch:** `Net11/Integration-2` (KlausLoeffelmann/winforms) +**Scope:** Code changes only. The GitHub proposal issue is handled by a separate work order +(`ApiReview-IssueUpdates.md`, Section 3) and run only after this implementation stands. +**Supersedes:** `Application.GetWindowsAccentColor` and the standalone accessibility text-size change +event currently on the branch (see item 6). + +--- + +## Background + +Windows delivers visual/accessibility setting changes through four channels — `WM_SETTINGCHANGE`, +`WM_DWMCOLORIZATIONCOLORCHANGED`, `WM_THEMECHANGED`, `WM_SYSCOLORCHANGE` — and today each consumer +normalizes that zoo individually. This work order introduces one typed, read-only snapshot plus one +unified change notification, with a **leak-free consumption path for controls** (virtual cascade, no +static-event subscription — the `SystemEvents.UserPreferenceChanged` leak class must be structurally +impossible for the default path). + +Deliberate non-goals, enforced by the type system: **no settable properties.** Perceptual adjustments +(contrast, color filtering, text scale, focus prominence, motion) are user-owned via Windows +accessibility settings; app-side theming is the business of control vendor partners. Renderers derive +output from this snapshot combined with `EffectiveVisualStylesMode`. + +--- + +## 1. New types (`System.Windows.Forms`) + +```csharp +public sealed class SystemVisualSettings +{ + public Color AccentColor { get; } + public float TextScaleFactor { get; } // 1.0–2.25, Windows a11y text scale + public bool HighContrastEnabled { get; } + public bool ClientAreaAnimationEnabled { get; } // SPI_GETCLIENTAREAANIMATION + public bool KeyboardCuesVisible { get; } // SPI_GETKEYBOARDCUES (system default) + public Size FocusBorderMetrics { get; } // SPI_GETFOCUSBORDERWIDTH/HEIGHT, pixels +} + +[Flags] +public enum SystemVisualSettingsCategories +{ + None = 0, + AccentColor = 1 << 0, + TextScale = 1 << 1, + HighContrast = 1 << 2, + Animations = 1 << 3, + KeyboardCues = 1 << 4, + FocusMetrics = 1 << 5 +} + +public class SystemVisualSettingsChangedEventArgs : EventArgs +{ + public SystemVisualSettings OldSettings { get; } + public SystemVisualSettings NewSettings { get; } + public SystemVisualSettingsCategories Changed { get; } +} +``` + +Immutable snapshot semantics — values must not shift under an event handler comparing old vs new. +XML remarks per the design notes: `HighContrastEnabled` cross-references the effective-mode clamp; +`KeyboardCuesVisible` documents the system-default vs per-window (`WM_UPDATEUISTATE`) distinction; +`FocusBorderMetrics` is documented as the baseline input for border/focus prominence in renderers +(scaled for DPI and `TextScaleFactor`), replacing fixed constants; the class remarks state the +no-app-side-overrides principle explicitly. + +## 2. `Application` surface + +```csharp +public static SystemVisualSettings SystemVisualSettings { get; } +public static event EventHandler? SystemVisualSettingsChanged; +``` + +Event XML remarks must state: (a) raised once per settings transition, normalized across the four +underlying messages; (b) handlers should early-out via `e.Changed`; (c) **audience is app-lifetime +consumers** (theming engines, services); components with shorter lifetime than the application must +unsubscribe; **controls and forms should use the `Control`-level virtual/instance event instead, +which requires no unsubscription** (see item 3). This positioning is the leak fix — make the +leak-free path the documented default. + +## 3. `Control`-level consumption (the leak-free path) + +```csharp +protected virtual void OnSystemVisualSettingsChanged(SystemVisualSettingsChangedEventArgs e); +public event EventHandler? SystemVisualSettingsChanged; +``` + +- Model the cascade on the existing `OnSystemColorsChanged` pattern in `Control.cs`: virtual + dispatch parent→children, instance event raised from within the virtual. No subscription to any + static event exists anywhere in this path — lifetime coupling is structural. +- Keep the cascade pattern-identical to `OnVisualStylesModeChanged` / `OnParentVisualStylesModeChanged` + (see the VisualStylesMode impact work order). A `HighContrast` category change resolves as an + effective-visual-styles-mode change for affected controls and must route through that machinery's + early-out/dispatch — no duplicate HC handling in this cascade. +- **Remove/replace the existing Form-level replicated text-size event**: it generalizes into this + cascade and disappears as a special case. Migrate in-box usages. +- Staleness rule (document in XML remarks, mirroring `OnSystemColorsChanged` folklore — this time + written down): the cascade only reaches parented controls; a control created but not yet parented + misses transitions and must re-query `Application.SystemVisualSettings` on handle creation / + `OnParentChanged`. + +## 4. Message plumbing and normalization + +Central internal tracker (e.g. `SystemVisualSettingsTracker`) holding the current snapshot: + +- Every **top-level** window already receives the four raw messages; handle them in the existing + top-level `WndProc` paths. +- On receipt: the window asks the tracker to re-query. The **first** arriver computes the diff + against the current snapshot, atomically swaps it (`Interlocked` reference swap), raises the static + `Application` event **once**, and cascades into its own tree. Subsequent top-levels re-query, see + no diff, raise nothing at Application level, but **still cascade into their own trees** using the + already-computed args. +- Threading falls out for free: each tree is notified on the thread owning its top-level — no + marshaling, correct for multi-message-loop applications. Do not centralize onto one thread. +- Coalesce message storms: a single user action can produce several of the four messages; debounce + within a message-pump iteration (re-query once per burst per top-level, not per message). + +## 5. In-box consumption cleanup + +- Audit in-box `Microsoft.Win32.SystemEvents` subscriptions (`UserPreferenceChanged` et al.) in + controls/renderers; migrate those covered by the new categories to the cascade. Document any that + must remain (categories outside this surface) — do not expand the snapshot to chase them in this + work order. +- `TextBoxBase` Net11 border rendering: consume `FocusBorderMetrics` + `TextScaleFactor` as the + border-prominence input where fixed constants are currently used (coordinate with the animation / + focus-indicator renderer as applicable). +- Animated renderers (`AnimatedControlRenderer` / `AnimationManager`): honor + `ClientAreaAnimationEnabled == false` by rendering final state immediately and suppressing + transitions; react to the `Animations` category change at runtime. + +## 6. Supersede the piecemeal APIs + +- `Application.GetWindowsAccentColor` → `Application.SystemVisualSettings.AccentColor`. The method + has not shipped stable: **remove it** on this branch (preferred) rather than obsoleting, to avoid + two sources of truth. If removal is blocked by preview-compat policy, `[Obsolete]` with pointer. +- The standalone text-size change event (Application- and/or Form-level) → `Changed.HasFlag(TextScale)` + on the unified event / cascade. Same removal-vs-obsolete decision, same preference. +- Migrate all in-box call sites. + +## 7. Tests + +- Snapshot immutability and correct SPI mapping per property (mock/native-shim as the repo's test + infra allows). +- Normalization: N top-level windows + one settings transition ⇒ exactly one Application-level raise; + every window's tree cascaded exactly once; delivery on each tree's own thread. +- Flags correctness per category, including multi-category transitions (HC toggle typically changes + colors + HC + metrics in one burst — must coalesce to one event with combined flags). +- Leak test: create/dispose forms subscribing to the **control-level** event in a loop; assert + collectability (`WeakReference`), proving no static rooting. Counter-test documenting that the + static event does root (expected, documented behavior). +- HC toggle end-to-end: cascade triggers effective-mode change path once, no duplicate layout. + +## Constraints + +- All new public surface XML-documented in the branch's voice; internal tracker fully internal. +- No settable members anywhere on the new types — if implementation pressure suggests one, stop and + flag rather than adding it. +- Windows-only P/Invoke via `LibraryImport`, gated per existing repo practice. diff --git a/.github/Feature-Prompts/Net11/03-B05-VisualStylesMode-ImpactApi-Implementation.md b/.github/Feature-Prompts/Net11/03-B05-VisualStylesMode-ImpactApi-Implementation.md new file mode 100644 index 00000000000..a1d56d1aa0b --- /dev/null +++ b/.github/Feature-Prompts/Net11/03-B05-VisualStylesMode-ImpactApi-Implementation.md @@ -0,0 +1,137 @@ +# Work Order: VisualStylesMode — Change-Impact API (Implementation) + +**Branch:** `Net11/Integration-2` (KlausLoeffelmann/winforms) +**Scope:** Code changes only. GitHub issue updates are handled by a separate work order +(`ApiReview-IssueUpdates.md`, Section 1) and run only after this implementation stands. +**Out of scope:** `HighPrecisionTimer` (separate work order), `SystemVisualSettings` (separate work order — +but see the composition note in item 4, the two cascades share a pattern). + +--- + +## Background + +The `VisualStylesMode` API is implemented on this branch. Two gaps motivate this change: + +1. **Correctness/ordering:** Base `Control.OnVisualStylesModeChanged` only invalidates, raises the + event, and cascades — no preferred-size cache invalidation, no layout transaction (unlike + `OnFontChanged`). Every metric-changing control reimplements a four-step protocol; `TextBoxBase` + currently runs `LayoutTransaction.DoLayoutIf(...)` **before** `UpdateStyles()`, so containers + measure against pre-transition metrics — a live mode switch clips/overlaps until controls are + recreated. +2. **Performance:** A top-level switch triggers one full parent layout per metric-affected control, + each against partially-transitioned state; repaint-only controls pay costs they don't need. + +Fix: a declarative impact model — derived controls state **what** changes, the base class owns +**how and in what order** to react, with one coalesced layout pass per container. + +--- + +## Changes + +### 1. `Control.cs` — visibility promotion + +`EffectiveVisualStylesMode`: `private protected` → `protected`. **Non-virtual** (deliberate — it is +the accessibility policy enforcement point; the customization hook is the already-virtual +`DefaultVisualStylesMode`). Extend XML docs: this is the value controls must honor for rendering; +reflects High Contrast (⇒ `Classic`) and `Disabled`; cross-reference `DefaultVisualStylesMode`. + +### 2. `Control.cs` — impact enum + virtual + +```csharp +protected enum VisualStylesModeChangeImpact +{ + None, // no rendering difference; skip all work + Repaint, // client-area rendering only; metrics identical + NonClientUpdate, // NC frame changes; style/frame update, no size change + Metrics // preferred size / layout metrics change; full invalidation + layout +} + +protected virtual VisualStylesModeChangeImpact GetVisualStylesModeChangeImpact( + VisualStylesMode oldMode, + VisualStylesMode newMode) + => VisualStylesModeChangeImpact.Repaint; +``` + +Parameters are **effective** modes. Document: implementations may consult instance state +(`Multiline`, `BorderStyle`, …) but the value must be stable for the duration of the change handling. + +### 3. `Control.cs` — setter early-out on effective equality + +In the `VisualStylesMode` setter and `OnParentVisualStylesModeChanged`: capture effective mode before +the change; if unchanged after, skip `OnVisualStylesModeChanged` entirely (no invalidate, no cascade +into that subtree). Preserve the existing shadowing behavior (child with explicit local value already +stops the ambient cascade) and add the effective-equality check on top. High Contrast active ⇒ raw +`Net11 → Latest` switch is a complete no-op. + +### 4. `Control.cs` — `OnVisualStylesModeChanged` becomes the dispatcher + +Preserve the disposal guard and public event raise. Then: + +- `impact = GetVisualStylesModeChangeImpact(oldEffective, newEffective)` — plumb old/new effective + values from the setter/cascade (least-invasive mechanism consistent with how `OnParentFontChanged` + plumbs state). +- `None` → raise event, skip rendering/layout work, still cascade (children's impact may differ). +- `Repaint` → `Invalidate()`. +- `NonClientUpdate` → `UpdateStyles()` + NC frame refresh (`SetWindowPos` + `FRAMECHANGED`, per the + branch's existing pattern), then `Invalidate()`. +- `Metrics` → in order: `CommonProperties.xClearPreferredSizeCache(this)` → `UpdateStyles()` / frame + refresh → layout deferred to the coalesced step: + +```csharp +if (ChildControls is { } children) +{ + using (new LayoutTransaction(this, this, PropertyNames.VisualStylesMode, resumeLayout: false)) + { + for (int i = 0; i < children.Count; i++) + { + children[i].OnParentVisualStylesModeChanged(e); + } + } +} + +LayoutTransaction.DoLayout(this, this, PropertyNames.VisualStylesMode); +``` + +Add `PropertyNames.VisualStylesMode` if missing. + +**Composition note:** the `SystemVisualSettings` work order introduces a structurally identical +parent→child cascade (`OnSystemVisualSettingsChanged`, modeled on `OnSystemColorsChanged`). Keep the +two cascades pattern-identical; a High Contrast toggle arriving via that path resolves here as an +effective-mode change and must take the same early-out/dispatch route — no duplicate handling. + +### 5. `TextBoxBase.cs` — adopt the model, delete the hand-rolled protocol + +- Override `GetVisualStylesModeChangeImpact`: crossing `Classic`/`Disabled` ↔ `>= Net11` ⇒ `Metrics` + (`PreferredHeight` selection and NC padding both change). Within `>= Net11` (`Net11 → Latest`) ⇒ + `Repaint` **unless** the branch's renderer shows metric differences between those modes — verify + against `PreferredHeightCore` and the NC padding tables; document the decision in XML remarks. +- Slim `OnVisualStylesModeChanged`: remove manual `xClearPreferredSizeCache` / `DoLayoutIf` / + `AdjustHeight` sequencing — base owns it. Keep control-specific work + (`_focusIndicatorRenderer?.Synchronize(...)`, `_triggerNewClientSizeRequest = false`), with the + ordering contract: latch reset **before** `base.OnVisualStylesModeChanged(e)` (which runs + `UpdateStyles()`); any residual `AdjustHeight` need goes **after** `base` — verify with the + live-switch repro (TableLayoutPanel, AutoSize rows, anchored single-line TextBoxes; runtime mode + switch; rows must resize without reopening the form). +- This closes the `DoLayoutIf(AutoSize: false)` hole: base-owned coalesced layout means + `AutoSize == false` TextBoxes no longer skip parent re-measurement. + +### 6. Documentation & tests + +- `docs/Net11Api_05_VisualStylesMode.HighRiskReview.md`: add the behavioral change (base + `OnVisualStylesModeChanged` now clears caches, updates styles, requests layout; overriders calling + `base` inherit this). If the branch's `WFCC`/`ComponentChange` infrastructure is present, annotate; + otherwise the high-risk doc entry suffices. +- `ControlTests.VisualStylesMode.cs`: + - effective-equality early-out (HC active ⇒ no event storm, no layout), + - default impact is `Repaint`, + - `Metrics` path clears preferred-size cache; exactly one layout per container for a multi-control + subtree switch (layout-count instrumentation or `LayoutEventArgs` assertion), + - `TextBoxBase` live-switch regression test: preferred-height change reflected in an AutoSize + `TableLayoutPanel` row without control recreation. + +## Constraints + +- No binary breaking changes (`protected` promotion + new `protected` members on unsealed public + class are additive). +- Do not change the `EffectiveVisualStylesMode` clamping logic. +- Match repo analyzers/style and the branch's XML-doc voice. diff --git a/.github/Feature-Prompts/Net11/Application.SystemTextAwareness/Application.SystemTextAwareness.md b/.github/Feature-Prompts/Net11/Application.SystemTextAwareness/Application.SystemTextAwareness.md new file mode 100644 index 00000000000..da7edcf854e --- /dev/null +++ b/.github/Feature-Prompts/Net11/Application.SystemTextAwareness/Application.SystemTextAwareness.md @@ -0,0 +1,180 @@ +# Task: Create a new API — `Application` system-text-size awareness — and the respective API proposal + +## What to do + +Create a **new API proposal / API review issue in the upstream `dotnet/winforms` repo** +(`origin` = my fork, `upstream` = the Microsoft repo where this lands). Write it per the +WinForms repo conventions and the relevant skills for authoring new-API issues. Apply the +skills; don't ask me for boilerplate. + +This proposal introduces **runtime awareness of the Windows Accessibility text-size +setting** at the `Application` level, plus a per-`Form` change notification. It is the +**foundation** proposal; a companion `TreeView.NodeLeading` proposal references this one. + +## Before you implement anything + +**Verify every premise below against current source before committing to the design.** +Verify, don't trust. If any premise is wrong, stop and tell me. Key files (VMR @ +`96982699e0dd8c046f397541dc0eb235ea8a4958`): + +- `src/winforms/src/System.Windows.Forms.Primitives/src/System/Windows/Forms/Internals/ScaleHelper.cs` +- `src/winforms/src/System.Windows.Forms/System/Windows/Forms/Application.cs` +- `src/winforms/src/System.Windows.Forms/System/Windows/Forms/Application.ThreadContext.cs` +- `src/winforms/src/System.Windows.Forms/System/Windows/Forms/Application.ParkingWindow.cs` +- `src/runtime/src/libraries/Microsoft.Win32.SystemEvents/...` (SystemEvents / UserPreferenceCategory) + +## Rationale — surface and complete an existing partial implementation + +This is **not** a net-new feature; it **finishes a half-built one**. WinForms already reads +the Accessibility text-size setting, but only once and only for the default font: + +`ScaleHelper.ScaleToSystemTextSize(Font?)` reads +`HKEY_CURRENT_USER\Software\Microsoft\Accessibility` → value `TextScaleFactor` +(REG_DWORD, clamped 100–225), and returns the font scaled by `TextScaleFactor / 100` +(or `null` if 100, if the font `IsSystemFont`, or if the OS is < Windows 10 1507). It is +documented in-source as the **Settings → Display → Make Text Bigger** setting. + +The gaps: (1) the value is **never surfaced** to developers; (2) it is read **once**, at +default-font construction, and the app **never reacts** when the user changes the setting at +runtime; (3) there is **no notification** mechanism. This proposal fills those three gaps. + +## Three-knob disambiguation (MANDATORY callout — reviewers will conflate these) + +Windows surfaces three *different* sizing mechanisms; the Settings UI even puts two on one +page (`System → Display → Custom scaling` shows a "Custom scaling 100–500%" box AND a +"Text size" link). The proposal MUST state plainly which one it targets: + +1. **Display / Custom scaling (100–500%)** → this is **DPI**. Already handled by + `HighDpiMode` and the DPI events (`WM_DPICHANGED`, `Control.DpiChanged*`). **NOT** this + proposal. +2. **Accessibility → Text size (100–225%)** → registry `TextScaleFactor` under + `HKCU\Software\Microsoft\Accessibility`; WinRT `UISettings.TextScaleFactor` / + `TextScaleFactorChanged`. **THIS is the target.** Independent of DPI. +3. **Legacy pre-Win10 per-element text sizing** (title bars/menus) → **removed** in Windows + 10 1703; the Accessibility slider replaced it. Mentioned only to close the loop. + +State explicitly that `Application.SystemTextSize` reflects **#2 only**, and is orthogonal to +DPI (#1). + +## Proposed API + +### `Application` (process-static) + +- **`public static double SystemTextSize { get; }`** — the current Accessibility text-scale + factor (1.0–2.25; i.e. `TextScaleFactor / 100`). **Live getter** — re-reads the value, does + not cache, because it is a system setting that changes at runtime. Well-defined regardless + of whether any `Form` exists or how many UI threads are running (it is process-global). +- **`public static SystemTextSizeAwareness SystemTextSizeAwareness { get; set; }`** — the + mode. **Enum, not bool**, deliberately, to reserve room for a future `Automatic`: + - `Unaware` (default) — no notification raised; fully back-compatible, nothing changes. + - `Notify` — raise change notifications (see below); the app decides how to respond. + - *(reserved, NOT implemented now: `Automatic` — framework re-flows for you. Reserving the + enum slot now avoids a future breaking bool→enum change, the same lesson `HighDpiMode` + learned.)* +- **`public static event EventHandler? SystemTextSizeChanged`** — fires once per process when + the setting changes (only when awareness is `Notify`). + +### `Form` (instance) + +- **`public event EventHandler? SystemTextSizeChanged`** — instance event, raised on each + top-level `Form` when the setting changes. +- **`protected virtual void OnSystemTextSizeChanged(EventArgs e)`** — overridable, fires the + instance event via the `EventHandlerList` pattern (`Events[s_systemTextSizeChangedEvent]`). + +## The trigger architecture (the leak-critical part — get this exactly right) + +A naive design — a static `Application.SystemTextSizeChanged` that `Form`s/`Control`s +subscribe to — **leaks**: the static event strongly roots every subscriber, so no `Form` +that subscribes is ever collected. Avoid this by **mirroring the DPI architecture**, where +`Control`/`Form` learn of DPI changes from their **own `WndProc`** (`WM_DPICHANGED` → +`OnDpiChanged` → instance event via `EventHandlerList`), **not** from a static subscription. + +Verified facts that constrain the design: + +- **`WM_SETTINGCHANGE` is broadcast** (`HWND_BROADCAST`) and delivered directly to top-level + windows' `WndProc`s — it bypasses the thread message queue, so **`IMessageFilter` does NOT + see it.** Do not use a message filter. +- **The WinForms parking window is message-only** (`CreateParams.Parent = HWND_MESSAGE`). + Message-only windows are **excluded from broadcasts**, so the parking window **cannot** + receive `WM_SETTINGCHANGE`. Do not use it. +- **`Application` has no `MainForm`.** The main form lives on `ApplicationContext` (per-run, + per-UI-thread), can be `null` (tray/loop-only apps), and is mutable (splash→main handoff). + So the main form is **not** a reliable receiver. Do not anchor the app-level event to it. +- **`SystemEvents` already owns a hidden top-level broadcast-receiving window** (its + `.NET-BroadcastEventWindow`), and exposes `UserPreferenceChanged` with a + `UserPreferenceCategory` (the relevant value is `Accessibility`, which is **coarse** — it + covers any accessibility change, so you must re-read `TextScaleFactor` and diff to confirm + it was text-scale). + +**Resulting design:** + +- **App-level:** `Application` makes **one internal, process-lifetime** subscription to + `SystemEvents.UserPreferenceChanged`, filters `Category == Accessibility`, re-reads + `TextScaleFactor`, diffs against the cached value, and if changed raises the static + `SystemTextSizeChanged`. This is a single framework-static→framework-static link — it does + **not** root any user object, so it is **not** the leak hazard. Reuses the existing hidden + broadcast window; **no new HWND** required. +- **Form-level:** each top-level `Form` handles `WM_SETTINGCHANGE` in its **own `WndProc`** + (it is a broadcast — every top-level window receives it), re-reads + diffs, and raises its + **instance** `SystemTextSizeChanged` via `OnSystemTextSizeChanged`. `Form`s do **not** + subscribe to `Application` — no rooting, lifetime = the window. + +Caveat to document: there is **no dedicated `WM_TEXTSCALECHANGED`** message. Both paths must +recognize a *relevant* change by re-reading `TextScaleFactor` and comparing, not by the +message alone. + +## Aids vs. leave-it-to-the-user + +**Notify-only. No automatic re-layout / font-rescaling aids in this proposal.** Reasons: +text scale interacts with `AutoScaleMode`, anchored/docked layout, and explicitly-set fonts +in app-specific ways; a generic "scale all fonts by the factor" helper breaks more than it +fixes. The reserved `Automatic` enum value is exactly where such behavior would live later. +`Notify` gives the developer the factor and the event; they decide. (Consistent with the +companion `NodeLeading` proposal's conservative-default philosophy.) + +## Why this matters across controls (evidence — include the matrix) + +Multiple text-measuring controls derive item/row/tile extents from a `Font` that today only +reacts to the text-size setting once at startup (via `ScaleToSystemTextSize` on the default +font) and never again. So **any single cached height scalar is wrong the moment text size +changes at runtime** — which is the core argument for runtime awareness: + +- **ListBox / ComboBox** — have `MeasureItem` + `OwnerDrawVariable` (a real per-item measure + hatch) and `ItemHeight`. Their gap is the legacy default base calc + the missing runtime + text-scale reaction — i.e. exactly this proposal. +- **TreeView** — has neither `MeasureItem` nor a wrapped native height API; only a uniform + native item height. Worst-positioned for a managed fix; addressed by the companion + `TreeView.NodeLeading` proposal, which depends on this one. +- **ListView (Details)** — no `MeasureItem`, no native row-height message; row height is + comctl-computed from `SmallImageList` + control font, while per-item/subitem fonts are + honored via `NM_CUSTOMDRAW` (`CDRF_NEWFONT`). Userland workarounds (phantom `SmallImageList`; + `LVS_OWNERDRAWFIXED` + one-shot reflected `WM_MEASUREITEM`; "inflate control font / shrink + item fonts") each have holes (header leak, set-once, exhaustive per-item font setting, + owner-draw-all). **No clean complete userland solution exists** — strengthening the case + that text-size reaction belongs in the framework. + +## XML doc requirements + +- Document that `SystemTextSize` is the **Accessibility text-size** factor (Settings → + Display → Make Text Bigger), **not** DPI/display scaling, and is process-global / live. +- Document the `Unaware`/`Notify` semantics and that `Automatic` is reserved for future use. +- Document the no-rooting design note on the static event (so consumers understand instance + vs. static). + +## Open questions for review + +- Should `SystemTextSize` be `double` (1.0–2.25) or expose the raw int percent (100–225)? +- Behavior on OS < Windows 10 1507 (where `ScaleToSystemTextSize` no-ops): `SystemTextSize` + returns 1.0 and no events fire? +- Whether to also expose the value/event on `Application` only, leaving `Form` consumers to + use their own `WndProc` override — or provide the `Form` instance event as proposed + (recommended, for parity with the DPI event model). + +## Output + +The upstream issue per the skills: summary; the "complete a partial implementation" +rationale; the mandatory three-knob disambiguation; the proposed API; the leak-safe trigger +architecture with the four verified constraints (broadcast vs. IMessageFilter, message-only +parking window, no MainForm on Application, SystemEvents reuse); Notify-only stance; the +cross-control matrix; XML-doc requirements; open questions. Flag anything the source +contradicts. diff --git a/.github/Feature-Prompts/Net11/Application/net11-VisualStylesMode/TextBoxBase-VisualStyles-WorkOrder.md b/.github/Feature-Prompts/Net11/Application/net11-VisualStylesMode/TextBoxBase-VisualStyles-WorkOrder.md new file mode 100644 index 00000000000..09894f9d23f --- /dev/null +++ b/.github/Feature-Prompts/Net11/Application/net11-VisualStylesMode/TextBoxBase-VisualStyles-WorkOrder.md @@ -0,0 +1,137 @@ +# Work Order — Port `TextBoxBase` NC-Painting + `VisualStylesMode` Chrome onto `VisualStylesNet11` + +**Target branch:** `KlausLoeffelmann/winforms` → `VisualStylesNet11` (current-`main`-based; modern path layout, no `/src/src/` doubling; `TextBoxBase.cs` ≈ 2130 lines). + +**Source of the original implementation (pinned):** `KlausLoeffelmann/winforms` @ `cf32e9c4efeba9d77e1a14025a8590b104e3c705` (old `/src/System.Windows.Forms/src/...` layout; `TextBoxBase.cs` ≈ 2562 lines). Relevant files: +- `.../Controls/TextBox/TextBoxBase.cs` — NC paint, NC calc, focus invalidation, `GetVisualStylesPadding`, helpers. +- `.../Controls/TextBox/TextBoxBase.NonClientBitmapCache.cs` — the offscreen cache class. +- `.../Controls/TextBox/TextBox.cs` — derived-level overrides (`CreateParams`, `WndProc`, `OnBackColorChanged`, `PRF_NONCLIENT` path). + +**Standing approval:** API review board sign-off from the .NET 9 cycle is still valid; DRI owns the call. This is a port + cleanup, **not** a redesign. Do not invent new public API beyond what the original exposed plus the `Padding` unshadowing called out below. + +**House style (apply throughout):** namespaces globally imported (no `using`/`imports` noise); C# 13/14; NRTs on; `var` only for long type names or when the type is obvious from the RHS, explicit type names for primitives; blank line between a new block and a following `return`; pattern matching / `is` / `and` / `or` / switch expressions preferred; collection expressions (`List x = [];`); expression-bodied members for single-line methods/read-only props formatted with the `=>` on the next line, 1-space-indented. Generate XML doc comments; use ``/``. + +--- + +## PROMPT 1 — Carry-over / Port + +> **Role:** You are porting a working-but-imperfect feature across a 3-year gap in the surrounding file. Faithfully reproduce the *mechanism*; do not improve, simplify, or "modernize" the algorithm except where this document explicitly says to. Where the surrounding `VisualStylesNet11` code has moved on, rebase onto the new shape rather than pasting. + +**Task.** Bring the non-client (NC) painting feature for `TextBoxBase` (and the `TextBox` derived touchpoints) from the pinned SHA `cf32e9c4…` onto `VisualStylesNet11`. The target branch currently has **none** of this work (no `WmNcPaint`/`WmNcCalcSize`/`OnNcPaint`/`GetVisualStylesPadding`/`NonClientBitmapCache`), but it **does** have the `VisualStylesMode` property infrastructure referenced in doc comments — wire into that, don't redeclare it. + +**Steps, in order:** + +1. **Fetch and diff the three source files** at SHA `cf32e9c4…` against their `VisualStylesNet11` counterparts. Produce a short inventory of every member you intend to add or modify, grouped by file, before writing any code. + +2. **Port `TextBoxBase.cs` members:** + - `WmNcPaint` / `OnNcPaint` (offscreen bitmap fill → AA rounded/single chrome → blit; `GetWindowDC`/`ReleaseDC` in `finally`). + - `WmNcCalcSize` (carves the padding band from `NCCALCSIZE_PARAMS->rgrc[0]`; gated on the `_triggerNewClientSizeRequest` latch). + - `InitializeClientArea` (the one-shot `SetWindowPos(SWP_FRAMECHANGED|NOMOVE|NOSIZE|NOZORDER|NOACTIVATE)` that provokes the single NC-calc). + - `GetVisualStylesPadding` / `GetScrollBarPadding` and the `VisualStyles{Fixed3D|FixedSingle|NoBorder}BorderPadding`, `BorderThickness` consts. + - The `WM_NCCALCSIZE` / `WM_NCPAINT` cases in `WndProc`. + - `OnGotFocus` / `OnLostFocus` / `OnSizeChanged` NC-frame invalidation (`RedrawWindow` with `RDW_FRAME|RDW_INVALIDATE`). + - `PreferredHeight` split (`PreferredHeightClassic` vs `PreferredHeightCore` selected by `VisualStylesMode`). + - Reconcile `GetPreferredSizeCore` with the modern branch already present on target. + +3. **Port `TextBoxBase.NonClientBitmapCache.cs`** — BUT this is a **decision point**, see Step 6. + +4. **Reconcile `TextBox.cs` (derived):** the target already has `CreateParams`, `WndProc`, `OnBackColorChanged` (special-casing `Fixed3D`), `OnGotFocus`, and a `WM_PRINTCLIENT`/`PRF_NONCLIENT` + `Application.RenderWithVisualStyles` path. Merge the NC behavior so the derived overrides cooperate with the new base NC painting (no double border draw, no fighting the `PRF_NONCLIENT` path). Call out every conflict you resolve. + +5. **Unshadow `Padding`.** On target it is still the neutered shadow (`[Browsable(false)]`, `EditorBrowsableState.Never`, `DesignerSerializationVisibility.Hidden`, `get/set => base.Padding`). Make it a real, browsable, serializable property that feeds the NC band via `GetVisualStylesPadding`. Preserve classic-mode behavior when `VisualStylesMode` is `Disabled`/`Classic`. Note the designer-serialization and back-compat implications in the PR description. + +6. **Retarget the rounded-rectangle helpers to the framework.** The original called fork-local `FillRoundedRectangle`/`DrawRoundedRectangle`. These now ship as **`System.Drawing.Graphics` instance methods** (`(Pen, Rectangle, Size)` + `RectangleF`/`SizeF` overloads; landed in the .NET 9 wave, current on target). **Delete the fork-local helpers and call the shipped methods.** ⚠️ Verify a **`FillRoundedRectangle(Brush, …)`** overload actually exists on target — the public ref only enumerates the `Draw`(`Pen`) overloads. If the `Fill`/`Brush` overload is absent, STOP and flag it; do not re-add a private helper without surfacing the gap. + +7. **Cache → `BufferedGraphics` (DECIDED — implement, do not re-evaluate).** The original used a hand-rolled per-instance `NonClientBitmapCache` (`CreateCompatibleBitmap` + `Image.FromHbitmap` + manual `DeleteObject`, `EnsureSize` realloc). Jeremy's late "use the existing cached bitmap" is confirmed to mean WinForms' own **`BufferedGraphics`/`BufferedGraphicsContext`** (the engine behind `OptimizedDoubleBuffer`; in `System.Drawing.Common` since .NET Framework 2.0, present on target). It is **not** `System.Drawing.Imaging.CachedBitmap` — that type is a read-only, device-dependent, blit-only frozen copy (no `Graphics`, translation-only, dies on bit-depth change) and cannot be a render target. **Delete `NonClientBitmapCache` entirely** (and its file `TextBoxBase.NonClientBitmapCache.cs`) and the `_cachedBitmap` field; replace with the shared buffer. Exact wiring: + - Inside `OnNcPaint`, get the shared context and allocate the buffer against the **window-DC `Graphics` already created in `WmNcPaint`**, sized to the window `bounds`: + `BufferedGraphicsContext context = BufferedGraphicsManager.Current;` + `using BufferedGraphics buffer = context.Allocate(graphics, bounds);` + `Graphics offscreenGraphics = buffer.Graphics;` + - **Do NOT `using`/dispose `buffer.Graphics`** — the `buffer` owns it; `using` the **buffer** only. (The original `using`-disposed its `GetNewGraphics()` because it owned that `Graphics`; that ownership is now the buffer's.) + - **All drawing into `offscreenGraphics` is unchanged** — the `FillRectangle(parentBackgroundBrush…)` corner-fill, the `BorderStyle` switch, the focus line: byte-for-byte identical, just a different `Graphics` target. + - **`ExcludeClip(clientBounds)` stays on the *target* `graphics`** (the window-DC one), exactly where it is now, set *before* the buffer draws. It governs where `Render()` may blit, protecting the client area — unchanged semantics. + - Replace the final blit `graphics.DrawImageUnscaled(offscreenBitmap, Point.Empty);` with **`buffer.Render();`** (no argument — it blits to the `graphics` captured at `Allocate` time). + - While here, fix the pre-existing **double-dispose** in `WmNcPaint`: it has both `using Graphics graphics = …` and an explicit `graphics.Dispose()` in `finally`. Drop the explicit `Dispose()`; keep the `using` (or keep explicit and drop `using` — one, not both). + - **Rationale to record in PR notes:** WinForms paints NC serially (one HWND at a time on the UI thread), so a single shared buffer suffices for any number of controls; the per-instance cache kept N resident GDI bitmaps to serve a one-deep queue. Steady-state allocation is unchanged (zero — shared buffer is reused when size fits); resident GDI memory drops from N× to 1×. The only cost is buffer-resize churn if controls of *wildly varying* sizes paint in a grow/shrink-alternating order — see smoke scenario 7 instrumentation. + +8. **Carve clamp + chrome degradation (settled design — implement exactly as stated, do NOT add a minimum size).** The original `WmNcCalcSize` does raw subtraction on `rgrc[0]` with **no clamp**, so a large `Padding` (made worse because `GetVisualStylesPadding(true)` *adds* the live scrollbar allowance from `GetScrollBarPadding` on top of the border padding) can drive the carved client rect to **zero or inverted**. Two separate fixes, and they are deliberately *not* a `MinimumSize`: + - **(8a) Never-invert clamp in `WmNcCalcSize`.** Floor each carved extent so the client rect can never invert: after the four adjustments, ensure `bottom >= top` and `right >= left` (e.g. clamp so the resulting client width/height is `Math.Max(0, …)`). A 0–1px client area is **acceptable and intended** — shipping multiline `TextBox` already shrinks to ~1px with scrollbars present, and we match that exactly. **Do NOT introduce a min-height/`MinimumSize`**, and do NOT make sizing behavior differ by `VisualStylesMode` (that would fracture the appearance-only contract of the opt-in). The clamp only prevents *underflow past zero*, which raw subtraction does and plain shrinking does not. + - **(8b) Paint-time chrome degradation in `OnNcPaint`.** The rounded `Fixed3D` chrome (15px radius) renders as a broken lozenge below roughly `2 × cornerRadius + BorderThickness` in height. When the available band/height is below that viable threshold, **fall back to the original/simple chrome render** (flat or single-style border) instead of the rounded path. This is a *rendering* fallback only — it does not change size or layout. Rationale on record: if the box is so small there's no usable client area, the control isn't usable anyway, so graceful visual degradation (not a size floor) is the correct response. + +9. **Build** `System.Windows.Forms` for the target TFM. Resolve all errors. Do not suppress new analyzer warnings without a one-line justification each. + +**Deliverable:** a single commit (or tight series) on `VisualStylesNet11` plus a PR description that lists: members added/modified per file, every `TextBox.cs` conflict resolved, confirmation that `NonClientBitmapCache` was removed and replaced by `BufferedGraphics` (Step 7) with the resize-churn rationale, the clamp/degradation (Step 8) confirmed as render-only with no size minimum, the `Padding` unshadowing implications, and any flagged gaps (Step 6 `Fill` overload). + +--- + +## PROMPT 2 — Critical Review (run AFTER Prompt 1, BEFORE smoke test) + +> **Role:** Adversarial reviewer. The author wants the issues a sharp WinForms maintainer would catch, not reassurance. Cite file + line for every finding. Classify each as **MUST-FIX**, **SHOULD-FIX**, or **PRESERVE (do not 'improve')**. + +Audit the ported code against this checklist. For each item, state the finding and the exact location. + +1. **DPI scaling of the corner radius.** The original hardcodes `const int cornerRadius = 15` and `BorderThickness = 1` in device-independent units, then uses them inside a DPI-scaled NC band, while `GetVisualStylesPadding` *does* take a DPI path (`_deviceDpi`). Confirm whether the radius/thickness now scale Per-Monitor-V2. If not → **MUST-FIX** (corners look proportionally too tight at 150/200%). + +2. **Full-frame NC repaint vs. partial `hrgnClip`.** `WmNcPaint` ignores the wParam clip region and repaints the whole frame. This is the **intended** fix for the offscreen-restore "dirty corners" artifact — verify it's preserved. But confirm `base.WndProc(ref m)` is still invoked with the original message and isn't double-painting the native border under the custom chrome. Classify the "ignore clip" behavior as **PRESERVE**. + +3. **Corner-blend source = `Parent?.BackColor ?? BackColor`.** This is the known ceiling: corners blend against the parent's flat back color, so they mismatch over a gradient/image/Mica/sibling. For the common case (solid form/panel) it's correct. **PRESERVE** — do not let it be "improved" into a fake general-case solution. Note it as a documented limitation only. + +4. **`WM_NCCALCSIZE` ↔ `Padding` round-trip + underflow.** Verify the band carved in `WmNcCalcSize` matches what `GetVisualStylesPadding(true)` reports and what `GetPreferredSizeCore`/`SizeFromClientSize` assume, for all three `BorderStyle` values × `Multiline` × scrollbars. Off-by-one here clips text or the caret. **Additionally** confirm the never-invert clamp (Prompt 1 Step 8a) is present and correct: with large `Padding` on a small multiline box *with both scrollbars*, the carved client rect must floor at 0, never invert. Remember the threshold is **border padding + live scrollbar padding** (`GetScrollBarPadding` reads `WS_HSCROLL`/`WS_VSCROLL`), so underflow hits sooner than the `Padding` value alone implies. Classify "0–1px client area is allowed, no min-size" as **PRESERVE** — do not let a reviewer or the agent add a `MinimumSize` floor. + +4b. **Chrome degradation below viable height.** Confirm `OnNcPaint` (Prompt 1 Step 8b) falls back to simple/flat chrome when height < ≈`2 × cornerRadius + BorderThickness`, instead of drawing a corrupted rounded rect. This is **render-only**; assert it does **not** alter size, layout, or `ClientSize`. Verify the fallback path itself is DPI-correct (the threshold scales with the radius, which per item 1 must scale). + +5. **`BorderStyle` fork + native edge suppression.** `Fixed3D` → rounded chrome, `FixedSingle` → single + underline, `None` → fill. Confirm the native `WS_EX_CLIENTEDGE`/`WS_BORDER` from `CreateParams` is suppressed when NC chrome is active, so the native edge isn't drawn under the custom one. + +6. **`VisualStylesMode` gating is total.** Every NC entry point (`WmNcPaint`, `WmNcCalcSize`, `InitializeClientArea`, the focus/size invalidations) must early-out to byte-for-byte classic behavior when `VisualStylesMode` is `Disabled`/`Classic`. One missing guard = a back-compat regression. Note the original's `OnLostFocus` was **missing** the guard that `OnGotFocus` had — verify the port fixed this asymmetry. + +7. **DC / GDI lifetime.** `GetWindowDC`→`ReleaseDC` in `finally`, and `Graphics.FromHdc`+`Dispose` ordering: correct **only** because `FromHdc` doesn't own the DC. **PRESERVE** — flag any "tidy into a single `using`" as a regression. Confirm the `WmNcPaint` **double-dispose** was fixed (it had both `using Graphics` and an explicit `graphics.Dispose()`). For the `BufferedGraphics` swap (Prompt 1 Step 7): verify the **buffer** is `using`-scoped but **`buffer.Graphics` is NOT separately disposed**; verify `Allocate` targets the window-DC `graphics` and `Render()` is called with no argument; confirm `NonClientBitmapCache` and the `_cachedBitmap` field are fully removed with no dangling refs. Audit for any HBITMAP/HDC leak in the new path (there should be none — the buffer owns it). + +8. **DPI-change without handle recreate.** `_triggerNewClientSizeRequest` is a one-shot latch reset on handle recreate. Does a DPI change that does *not* recreate the handle re-carve the band with new padding? If the band can go stale on monitor move → **MUST-FIX** or at least an explicit tracked issue. + +9. **Caret / IME / selection repaint.** The native `EDIT` invalidates aggressively. Confirm NC chrome doesn't go stale on caret blink/IME composition, and conversely that NC isn't thrashing-repainting on every caret tick. (Author never confirmed this was clean in the original.) + +10. **`TextBox.cs` derived reconciliation.** Verify the derived `WndProc`, `OnBackColorChanged` `Fixed3D` special-case, and the `PRF_NONCLIENT`/`Application.RenderWithVisualStyles` path don't conflict with base NC painting (double draw, wrong-mode paint). + +11. **Allocation churn.** Brushes/pens use cached scopes (`GetCachedSolidBrushScope`/`GetCachedPenScope`) — good; confirm preserved. Confirm the offscreen surface isn't reallocated per paint (only on size change). + +**Deliverable:** a findings list (file:line, severity, recommendation). MUST-FIX items get fixed in this pass; SHOULD-FIX either fixed or filed; PRESERVE items annotated in code with a brief `// Intentional:` comment so the next reader doesn't "fix" them. + +--- + +## PROMPT 3 — Smoke Test Harness + +> *("Smoke test" = the shallow "does it power on without catching fire" pass — from hardware bring-up, where first power-on literally checked for smoke — run before any deep/perf testing. Goal here: broad coverage that it comes up and behaves on the obvious axes, with the two known-fragile cases as explicit named tests.)* + +**Task.** Build a throwaway WinForms test app (separate project, not shipped) that exercises the ported feature across its permutation space and **specifically reproduces the two regressions this feature is prone to.** + +**Permutation grid** — generate a form populated with `TextBox`es (and at least one `RichTextBox`, since `TextBoxBase` is the shared base) covering the cross-product of: +- `BorderStyle`: `None` × `FixedSingle` × `Fixed3D` +- `Multiline`: `false` × `true` (+ `WordWrap` on/off for multiline) +- `Padding`: `Empty` × asymmetric (e.g. `2,6,2,6`) × large (`12`) +- Scrollbars: none × vertical × both +- `VisualStylesMode`: `Disabled`/`Classic` (must look exactly like today) × `Net10`+ (new chrome) +- Focused vs unfocused (drive focus programmatically to capture the adorner/underline) + +**Named, must-pass scenarios (the ones that silently regress):** + +1. **Offscreen-restore ("dirty corners").** Move the window partly off the left/top screen edge, then back. Assert the NC corner regions are repainted clean (no stale pixels). This is the artifact that drove the full-frame-repaint design. Automate the drag via `SetWindowPos`/`MoveWindow`; capture before/after. + +2. **Partial NC invalidation.** Trigger a partial `WM_NCPAINT` (e.g. overlap then reveal a sliver of the frame) and assert the whole chrome is coherent, not just the revealed strip. + +3. **Per-Monitor-V2 DPI.** Run DPI-aware; move forms between a 100% and a 150%/200% monitor (or fake via `LogicalToDeviceUnits`/DPI-changed messages). Assert corner radius, border thickness, and padding band all scale; assert no clipped text/caret. + +4. **Classic-mode parity.** With `VisualStylesMode = Disabled`, assert the control is pixel-identical to baseline `main` (native edge, no custom NC). A regression here is the back-compat line breaking. + +5. **`BorderStyle` switch at runtime** (`Fixed3D`↔`FixedSingle`↔`None`) and **`Padding` change at runtime** — assert the band re-carves and chrome redraws without artifacts (exercises the `_triggerNewClientSizeRequest` reset path). + +6. **Focus transitions** — tab through the grid; assert the focus underline (single) / 3D focus line (Fixed3D, shortened to clear the corner curve) appears/clears correctly. + +7. **Shrink-to-collapse (clamp + degradation).** Take a multiline `Fixed3D` box with large `Padding` (e.g. `12`) and **both** scrollbars visible, then programmatically drag/resize its height down toward 1px. Assert: (a) **no crash / no inverted client rect** handed to the native `EDIT` — the carve floors at 0 (Step 8a); (b) below ≈`2 × cornerRadius + thickness` the chrome **falls back to flat/simple render** rather than drawing a corrupted lozenge (Step 8b); (c) the control **still collapses** to ~1px exactly like classic multiline — assert it is **not** held open by any min-size (regression if a floor appeared). Repeat at 150%/200% DPI so the degradation threshold is verified scaled, not fixed at 96-dpi pixels. + +8. **BufferedGraphics allocation churn (perf sanity).** Build two forms: (a) **40 same-size** textboxes, (b) **40 wildly varying-size** textboxes (mix tiny and large), all `VisualStylesMode ≥ Net10`. Force a full repaint storm (invalidate all NC frames repeatedly; resize the form to cascade re-layout). Instrument the shared buffer: wrap/observe `BufferedGraphicsManager.Current` and count actual **bitmap (re)allocations** vs. reuses across the storm. Assert: case (a) allocates the buffer ≈once then reuses (steady-state alloc ≈ 0); case (b) may reallocate on grow but must **not** allocate-per-paint. Log alloc count per case. This empirically confirms the shared-buffer reasoning from Prompt 1 Step 7 and catches any accidental per-paint allocation regression. + +**Harness mechanics:** +- A "capture all" button that screenshots each form to disk per `VisualStylesMode`, for eyeball diffing classic-vs-modern and pre-vs-post-DPI. +- A console/log line per assertion (pass/fail) so it can run semi-automated. +- Keep it dependency-light: raw WinForms + `SetWindowPos`/`RedrawWindow` P/Invoke for the offscreen and invalidation drivers. + +**Deliverable:** the test project + a one-screen README naming the six scenarios and how to run them, plus a results log from one full run on the porter's machine (note DPI of monitors used). diff --git a/.github/Feature-Prompts/Net11/SuspendRelocationPaintingFlashPreventing/Create-Github-API-Proposal-Prompt.md b/.github/Feature-Prompts/Net11/SuspendRelocationPaintingFlashPreventing/Create-Github-API-Proposal-Prompt.md new file mode 100644 index 00000000000..ce3ad461cab --- /dev/null +++ b/.github/Feature-Prompts/Net11/SuspendRelocationPaintingFlashPreventing/Create-Github-API-Proposal-Prompt.md @@ -0,0 +1,120 @@ +# Copilot Prompt 1 — Author the WinForms API Suggestion + +## Your task + +Write a complete API suggestion for the `dotnet/winforms` repository, ready to be filed +as a GitHub issue with the `api-suggestion` label. The issue covers two related features +for reducing visible intermediate states while WinForms applications update their UI: + +1. Painting suspension with optional layout suspension across a control tree. +2. Deferred top-level form reveal. + +Use these issue sections: + +- `## Rationale` +- `## API Proposal` +- `## API Usage` +- `## Alternative Designs` +- `## Risks` +- `## Will this feature affect UI controls?` +- `### Status Checklist` + +## Sub-feature A — painting and layout suspension + +### Settled API surface + +```csharp +namespace System.Windows.Forms; + +public interface ISupportSuspendPainting +{ + void BeginSuspendPainting(); + void EndSuspendPainting(); +} + +public enum LayoutSuspendTraversal +{ + None = 0, + TopLevelOnly = 1, + Traverse = 2, +} + +public sealed class SuspendPaintingScope : IDisposable +{ + public SuspendPaintingScope(ISupportSuspendPainting? target); + public void Dispose(); +} + +public static class ControlMutationExtensions +{ + public static SuspendPaintingScope SuspendPainting( + this ISupportSuspendPainting target); + + public static SuspendPaintingScope SuspendPainting( + this ISupportSuspendPainting target, + LayoutSuspendTraversal layoutSuspendTraversal); + + public static SuspendPaintingScope SuspendPainting( + this ISupportSuspendPainting target, + Func suspendLayoutContainerFilter); +} +``` + +- `Control` implements `ISupportSuspendPainting` explicitly and exposes protected virtual + `BeginSuspendPaintingCore` / `EndSuspendPaintingCore` hooks. +- `ListView`, `ListBox`, `ComboBox`, `TreeView`, and `RichTextBox` route painting + suspension through their existing `BeginUpdate` / `EndUpdate` paths. +- `None` suspends painting only. +- `TopLevelOnly` suspends layout on the target `Control`. +- `Traverse` suspends layout on the target and all existing descendants. +- The predicate is evaluated for the target and every descendant. A `false` result skips + that node but does not prune traversal. +- Selected nodes are suspended even when they currently have no children. +- Layout-aware overloads require the target to derive from `Control`. +- The scope is a sealed class so it can span `await`. + +### Design considerations + +- Snapshot the selected controls when the scope starts. +- Suspend layout root-to-leaf and resume it deepest-first. +- Resume layout before ending painting so recursive invalidation occurs after layout. +- Keep disposal idempotent and preserve nesting through the existing ref counts. +- Explain that controls added after the snapshot are covered by their parent's suspended + layout but do not receive an independently balanced suspension. +- Discuss traversal cost for large control trees and exceptions thrown by predicates. +- Include invalid and non-`Control` target behavior in the proposal. + +## Sub-feature B — deferred form reveal + +Use the current `FormRevealMode` design from the tracked API proposal: + +```csharp +namespace System.Windows.Forms; + +public enum FormRevealMode +{ + Inherit = -1, + Classic = 0, + Deferred = 1, +} + +public partial class Form +{ + public virtual FormRevealMode FormRevealMode { get; set; } +} + +public partial class Application +{ + public static FormRevealMode DefaultFormRevealMode { get; } + public static void SetDefaultFormRevealMode(FormRevealMode mode); + public static bool IsFormRevealDeferred { get; } +} +``` + +Describe DWM cloaking, dark-mode-aware default resolution, designer serialization, +top-level-window limitations, and conservative fallback behavior on unsupported systems. + +## Filing instruction + +Produce a complete proposal rather than an implementation plan. Clearly distinguish fixed +API shape from implementation choices that remain open for review. diff --git a/.github/Feature-Prompts/Net11/SuspendRelocationPaintingFlashPreventing/SuspendRelocationAndPainting-API-Feature-Prompt.md b/.github/Feature-Prompts/Net11/SuspendRelocationPaintingFlashPreventing/SuspendRelocationAndPainting-API-Feature-Prompt.md new file mode 100644 index 00000000000..35d765ad3ce --- /dev/null +++ b/.github/Feature-Prompts/Net11/SuspendRelocationPaintingFlashPreventing/SuspendRelocationAndPainting-API-Feature-Prompt.md @@ -0,0 +1,76 @@ +# Copilot Prompt 2 — Implement the flicker-free UI mutation APIs + +## Prerequisite + +Read the current upstream API suggestion before implementation. Treat its latest +`API Proposal` section as the public contract and report any conflict instead of silently +choosing a different shape. + +## Scope + +### A — painting suspension with optional layout traversal + +- Implement `ISupportSuspendPainting` on `Control` with ref-counted + `BeginSuspendPaintingCore` / `EndSuspendPaintingCore` hooks. +- Route `ListView`, `ListBox`, `ComboBox`, `TreeView`, and `RichTextBox` through their + existing `BeginUpdate` / `EndUpdate` mechanisms. +- Keep `SuspendPaintingScope` as a sealed, idempotent `IDisposable` class so it can span + `await`. +- Provide these extension methods: + + ```csharp + public static SuspendPaintingScope SuspendPainting( + this ISupportSuspendPainting target); + + public static SuspendPaintingScope SuspendPainting( + this ISupportSuspendPainting target, + LayoutSuspendTraversal layoutSuspendTraversal); + + public static SuspendPaintingScope SuspendPainting( + this ISupportSuspendPainting target, + Func suspendLayoutContainerFilter); + ``` + +- `LayoutSuspendTraversal` has `None`, `TopLevelOnly`, and `Traverse`. +- Snapshot selected controls before suspension. Suspend root-to-leaf and resume + deepest-first. +- The predicate is evaluated for the target and every descendant. A `false` result skips + suspension for that node without pruning its descendants. +- Suspend selected controls even when they currently have no children. +- Validate layout-aware calls before beginning painting. A non-`Control` target is invalid. +- Resume all selected layout scopes before ending painting so the recursive invalidation + occurs after layout. + +### B — deferred form reveal + +- Implement the approved `FormRevealMode`, `Form.FormRevealMode`, and + `Application` configuration APIs. +- Preserve classic behavior when deferred reveal is not active. +- Cloak eligible top-level form handles and uncloak according to the timing strategy in the + proposal. +- Keep unsupported DWM and window configurations inert and safe. + +## Engineering requirements + +- Match the current repository language version, nullable annotations, code style, and + interop conventions. +- Add XML documentation for every public or protected API. +- Update `PublicAPI.Unshipped.txt`. +- Keep state lazy where existing `Control` property-store patterns apply. +- Do not change existing public `BeginUpdate` / `EndUpdate` behavior. + +## Tests + +- Painting ref-count balance, nesting, idempotent disposal, handle creation, and handle + recreation. +- `None`, `TopLevelOnly`, and `Traverse` layout selection. +- Predicate selection, continued traversal after a rejected node, and empty containers. +- Deepest-first layout resume and recursive invalidation after layout. +- Null, invalid-enum, and non-`Control` target failures without partial suspension. +- Existing native update paths for the selected built-in controls. +- Classic/deferred form reveal behavior and unsupported-OS fallback. + +## Deliverable + +Provide production code, focused tests, updated API tracking, and an updated API proposal. +Call out any behavior that the implementation proves unsafe or unnecessarily costly. diff --git a/.github/copilot/Async/invokeAsync_generate_test_instructions.md b/.github/Feature-Prompts/Net9/Async/invokeAsync_generate_test_instructions.md similarity index 100% rename from .github/copilot/Async/invokeAsync_generate_test_instructions.md rename to .github/Feature-Prompts/Net9/Async/invokeAsync_generate_test_instructions.md diff --git a/.github/copilot/GDI/DarkModeButtonRendererCodeGenerationInstructions.md b/.github/Feature-Prompts/Net9/GDI/DarkModeButtonRendererCodeGenerationInstructions.md similarity index 100% rename from .github/copilot/GDI/DarkModeButtonRendererCodeGenerationInstructions.md rename to .github/Feature-Prompts/Net9/GDI/DarkModeButtonRendererCodeGenerationInstructions.md From d0b5a4e144ef76ace4f771fcee494ce1f65f2070 Mon Sep 17 00:00:00 2001 From: Klaus Loeffelmann Date: Sat, 13 Jun 2026 13:26:48 -0700 Subject: [PATCH 02/69] Update agent skills: build.cmd build tenet, PublicAPI override tracking, and test cancellation/nullable guidance - building-code: add a top-level TENET to build the solution only with build.cmd (CI parity for PublicAPI/analyzer enforcement and -warnAsError); a plain dotnet build is inner-loop only. - new-control-api: new public/protected overrides must be tracked in PublicAPI.Unshipped.txt with the override prefix; note CS0114 (new keyword) and CS1574 (no cref to cross-assembly internal types). - control-api-tests: async tests must pass CancellationToken (TestContext.Current.CancellationToken, CA2016/xUnit1051) and respect the #nullable context (CS8632). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/skills/building-code/SKILL.md | 78 ++++++++++++++ .github/skills/control-api-tests/SKILL.md | 22 ++++ .github/skills/new-control-api/SKILL.md | 124 +++++++++++++++------- 3 files changed, 187 insertions(+), 37 deletions(-) diff --git a/.github/skills/building-code/SKILL.md b/.github/skills/building-code/SKILL.md index 040dd437081..67fd8c7ba30 100644 --- a/.github/skills/building-code/SKILL.md +++ b/.github/skills/building-code/SKILL.md @@ -11,6 +11,22 @@ metadata: # Building the WinForms Repository +> ## 🛑 TENET — Build the solution ONLY with `build.cmd` +> +> **Never** build, validate, or declare the WinForms solution "clean" with a plain +> `dotnet build` / `dotnet msbuild` of `Winforms.sln`. Only **`build.cmd`** (Arcade) applies the +> repository's CI configuration — the **PublicAPI analyzer (RS0016/RS0017)**, the code-style and +> documentation analyzers, and **`-warnAsError`**. A plain `dotnet build` silently downgrades or +> skips these, so **"0 warnings" there does NOT mean CI is green** — the very same change can fail +> the official build with errors. +> +> * **Full / release / package / "is it clean?" verification → always `build.cmd`** (see §2). +> * A single-project `dotnet build` (see §3) is an **inner-loop convenience only**. It is fine while +> iterating, but you **must re-verify with `build.cmd` before claiming a change builds cleanly**. +> * If `build.cmd` cannot run in your environment, the closest fallback is +> `dotnet build /p:ContinuousIntegrationBuild=true /p:TreatWarningsAsErrors=true` — and +> you must say so explicitly rather than implying a `build.cmd` result. + ## Prerequisites * Windows is required for WinForms runtime scenarios, test execution, and Visual @@ -45,6 +61,12 @@ You can pass any extra `Build.ps1` flags after `Restore.cmd`, e.g. ## 2 Full Solution Build (preferred) +> **Always use `build.cmd` (Arcade) for full, release, and package builds.** Do **not** use a plain +> `dotnet build` of the solution for these — only `build.cmd` guarantees the Arcade-supported build +> options and the download of the correct base SDK (`global.json`) needed to compile. Plain +> `dotnet build` is reserved for the fast single-project inner loop (see Section 3), and even then +> only after at least one successful `build.cmd` / `Restore.cmd`. + ``` .\build.cmd ``` @@ -57,6 +79,56 @@ Under the hood this runs: eng\common\Build.ps1 -NativeToolsOnMachine -restore -build -bl ``` +### 2.1 Full (clean) test build — required workflow + +For a full, clean build of the whole solution, **clean the artifacts first, then build**: + +```powershell +# 1. Clean the artifacts folder. +.\build -clean + +# 2. Build the full solution. +.\build +``` + +**Reporting requirement:** a full build is long-running, so while it runs **report progress back to +the user in the console to bridge the wait and give early orientation.** As assemblies complete, +report which assemblies have been **built successfully** and which **failed and with how many +errors**. Prefer running the build with a binary log (the default `-bl`) and/or stream the console +output so per-project results can be surfaced as they happen rather than only at the end. + +### 2.2 Release build + +```powershell +.\build -configuration release +``` + +### 2.3 Creating packages + +```powershell +# Debug packages +.\build -pack + +# Release packages +.\build -configuration release -pack +``` + +### 2.4 Full `Build.ps1` parameter list + +`build.cmd` forwards every extra argument to `eng\common\Build.ps1`. The full surface is: + +``` +Build.ps1 [-configuration ] [-platform ] [-projects ] + [-verbosity ] [-msbuildEngine ] [-warnAsError ] + [-warnNotAsError ] [-nodeReuse ] [-buildCheck] [-restore] + [-deployDeps] [-build] [-rebuild] [-deploy] [-test] [-integrationTest] + [-performanceTest] [-sign] [-pack] [-publish] [-clean] [-productBuild] + [-fromVMR] [-binaryLog] [-binaryLogName ] [-excludeCIBinarylog] + [-ci] [-prepareMachine] [-runtimeSourceFeed ] + [-runtimeSourceFeedKey ] [-excludePrereleaseVS] + [-nativeToolsOnMachine] [-help] [-properties ] [] +``` + ### Common flags | Flag | Short | Description | @@ -90,6 +162,12 @@ eng\common\Build.ps1 -NativeToolsOnMachine -restore -build -bl ## 3 Optimized Building a Single Project (fast inner-loop) +> **Inner-loop only.** Use plain `dotnet build` of a single project **only** for quick iteration on +> one project, and **only after** at least one successful `.\build.cmd` / `.\Restore.cmd`. It does +> **not** guarantee the Arcade-supported build options or the download of the correct base SDK, so it +> must **never** be used for a full solution build, a release build, packaging, or any build whose +> result you intend to report as authoritative. For those, always use `build.cmd` (Section 2). + Prefer rebuilding just the project(s) with recent changes by using the standard `dotnet build` command, **after** at least one initial successful full restore (via `.\Restore.cmd` or `.\build.cmd`). diff --git a/.github/skills/control-api-tests/SKILL.md b/.github/skills/control-api-tests/SKILL.md index 5badcc2547c..ff4e9304230 100644 --- a/.github/skills/control-api-tests/SKILL.md +++ b/.github/skills/control-api-tests/SKILL.md @@ -66,6 +66,28 @@ The project uses **xUnit** with **FluentAssertions**. Key attributes: These are custom xUnit attributes that ensure tests run on an STA thread, which WinForms requires for COM interop and UI operations. +### 1.4 Async tests: pass a CancellationToken, respect `#nullable` + +The repository runs **xUnit v3** and enforces the relevant analyzers as **errors** under the CI +build (`build.cmd`). Two pitfalls fail CI even though a plain `dotnet build` may not flag them: + +* **CA2016 / xUnit1051 — always pass a `CancellationToken` to async calls.** Methods such as + `Task.Delay` must receive a token so a cancelled test run stops promptly. In xUnit v3 use + `TestContext.Current.CancellationToken`: + + ```csharp + await Task.Delay(25, TestContext.Current.CancellationToken); + ``` + + When you receive a `CancellationToken ct` (e.g. in a callback), **forward it** rather than dropping it. + +* **CS8632 — nullable annotations need a `#nullable` context.** If a test file uses `?` reference + annotations (e.g. `object? sender`) but the project does not enable nullable, add `#nullable enable` + at the top of the file (or remove the annotation). Match the surrounding files' convention. + +> Verify with `build.cmd` (CI parity) — see the `building-code` skill's build tenet. A plain +> single-project `dotnet build` can report these as 0 warnings while CI fails them as errors. + --- ## 2. Test Method Naming diff --git a/.github/skills/new-control-api/SKILL.md b/.github/skills/new-control-api/SKILL.md index ce6c58b6d2e..3030cf92ef7 100644 --- a/.github/skills/new-control-api/SKILL.md +++ b/.github/skills/new-control-api/SKILL.md @@ -148,7 +148,34 @@ System.Windows.Forms.MyEnum.Value2 = 1 -> System.Windows.Forms.MyEnum **Nullable annotations:** `?` = nullable reference, `!` = non-nullable reference. Value types do not carry these markers unless `Nullable`. -### 2.4 Publicly accessible interfaces +### 2.4 New `override` members must be tracked too + +The PublicAPI analyzer (RS0016) treats a **newly introduced `override`** of a public or +protected member as new API surface — even though the base member is already public. Whenever +you **add an `override` that did not previously exist on that type**, add a line for it to +`PublicAPI.Unshipped.txt` with the `override` prefix. This is easy to miss for paint/lifecycle +overrides added to support a feature. Examples: + +```text +override System.Windows.Forms.CheckBox.OnPaint(System.Windows.Forms.PaintEventArgs! pevent) -> void +override System.Windows.Forms.CheckBox.Dispose(bool disposing) -> void +override System.Windows.Forms.ButtonBase.OnVisualStylesModeChanged(System.EventArgs! e) -> void +``` + +> **CI catches this, a plain `dotnet build` may not.** RS0016 is enforced as an **error** under +> the CI/Arcade build (`build.cmd`); a single-project `dotnet build` can report it as 0 warnings. +> Always re-verify API tracking with `build.cmd` (see the `building-code` skill's build tenet). + +### 2.5 Related pitfalls when adding members to a control + +* **Hiding an inherited member (CS0114):** if your new member intentionally hides an inherited + one (e.g. a `private new bool ShouldSerializePadding()` shadowing `Control.ShouldSerializePadding()`), + you **must** use the `new` keyword, or the CI build fails. +* **`cref` to internal types in another assembly (CS1574):** XML-doc `` cannot + resolve a type that is `internal` in a *different* assembly (even via `InternalsVisibleTo`). Use + `TypeName` (plain code font) instead of a `cref` for such references. + +### 2.6 Publicly accessible interfaces If a new **public or protected interface** is introduced (or an existing one gains new members), every member that is publicly accessible must also appear @@ -468,51 +495,73 @@ protected virtual void OnMyPropertyChanged(EventArgs e) --- -## 7. .NET Version Guard — Mandatory +## 7. API Stability: Experimental vs. Stable — and Version Guards -All new public APIs **must** be guarded with a preprocessor directive for the -target .NET version. Currently, new APIs target at least **.NET 11**: +### 7.1 New APIs are STABLE by default — do NOT mark them `[Experimental]` -```csharp -#if NET11_0_OR_GREATER - /// - /// Gets or sets the corner radius for the control's border. - /// - public int CornerRadius - { - get => Properties.GetValueOrDefault(s_cornerRadiusProperty, 0); - set - { - ArgumentOutOfRangeException.ThrowIfNegative(value); +New public APIs ship as **normal, stable APIs by default**. Do **not** add the +`[Experimental(...)]` attribute, a `WFO5xxx` diagnostic ID, or `[WFO5xxx]` +PublicAPI prefixes unless the work item **explicitly** asks for an experimental +API. - if (Properties.GetValueOrDefault(s_cornerRadiusProperty, 0) != value) - { - Properties.AddOrRemoveValue(s_cornerRadiusProperty, value, defaultValue: 0); - OnCornerRadiusChanged(EventArgs.Empty); - } - } - } -#endif -``` +> **Never make an API experimental implicitly.** Experimental status is a +> deliberate, requested decision (it changes the customer contract and requires a +> diagnostic ID + suppression to consume). If the context does not explicitly call +> for it, the API is stable. + +### 7.2 When an experimental API *is* explicitly requested + +Only when the task explicitly requests an experimental API: + +1. Add (or reuse) a diagnostic ID in the `WFO500x` group in + `src\System.Windows.Forms.Analyzers\src\System\Windows\Forms\Analyzers\Diagnostics\DiagnosticIDs.cs` + (e.g. `ExperimentalDarkMode = "WFO5001"`, `ExperimentalAsync = "WFO5002"`, + `ExperimentalAsyncDropTarget = "WFO5003"`). New IDs continue the sequence. +2. Decorate the API: + ```csharp + [Experimental(DiagnosticIDs.ExperimentalXxx, UrlFormat = DiagnosticIDs.UrlFormat)] + ``` +3. Prefix every PublicAPI entry for that API with the diagnostic ID, e.g. + `[WFO5001]System.Windows.Forms.SomeNewApi.get -> ...`. +4. Add a row to **both** `docs\analyzers\Experimental.Help.md` and + `docs\list-of-diagnostics.md`. +5. Suppress the diagnostic where the framework itself consumes the API + (`#pragma warning disable WFOxxxx` / `#Disable Warning WFOxxxx` in VB). -> **Why?** Version guards ensure new APIs are only available on the .NET version -> they were approved for, preventing accidental use on older runtimes. The guard -> applies to the entire API surface: property, event, `On` method, and any -> associated types. +When the API later **graduates to stable** (typically the next release), reverse +all five steps: remove the attribute, the `[WFOxxxx]` PublicAPI prefixes, the +suppressions, the docs rows, and the unused diagnostic ID. -The matching tests must use the **same** preprocessor guard: +### 7.3 Version guards + +This repository **single-targets the current in-development .NET** (see +`TargetFramework` / `NetCurrent`), so source is **not** wrapped in +`#if NETxx_0_OR_GREATER` guards — there are none in `System.Windows.Forms`. Do +**not** add `#if NET11_0_OR_GREATER` blocks around new APIs. Add the member +directly: ```csharp -#if NET11_0_OR_GREATER - [WinFormsFact] - public void MyControl_CornerRadius_Set_GetReturnsExpected() +/// +/// Gets or sets the corner radius for the control's border. +/// +public int CornerRadius +{ + get => Properties.GetValueOrDefault(s_cornerRadiusProperty, 0); + set { - using MyControl control = new() { CornerRadius = 5 }; - Assert.Equal(5, control.CornerRadius); + ArgumentOutOfRangeException.ThrowIfNegative(value); + + if (Properties.GetValueOrDefault(s_cornerRadiusProperty, 0) != value) + { + Properties.AddOrRemoveValue(s_cornerRadiusProperty, value, defaultValue: 0); + OnCornerRadiusChanged(EventArgs.Empty); + } } -#endif +} ``` +Tests do not need a version guard either. + --- ## 8. Checklist Before Submitting @@ -521,7 +570,8 @@ Before considering the implementation complete, verify: * [ ] API proposal issue exists (upstream or fork) with full proposal format * [ ] All new public/protected members are in `PublicAPI.Unshipped.txt` -* [ ] New APIs guarded with `#if NET11_0_OR_GREATER` (or appropriate version) +* [ ] API is **stable** (no `[Experimental]`/`WFO5xxx`) unless experimental was + explicitly requested; no `#if NETxx_0_OR_GREATER` guards * [ ] Property values stored via `PropertyStore` (not backing fields) * [ ] Every property has a CodeDOM serialization strategy * [ ] Every property has `On[Property]Changed` + `[Property]Changed` event @@ -533,7 +583,7 @@ Before considering the implementation complete, verify: * [ ] XML documentation on every new public/protected member * [ ] Naming follows precedent on the control and its base classes * [ ] Publicly accessible interface members are tracked in PublicAPI files -* [ ] Unit tests cover the new API surface (with matching version guard) +* [ ] Unit tests cover the new API surface ### 8.1 API issue checklist From 308f5a841964a9ac48afcd0d71d5655409dbb290 Mon Sep 17 00:00:00 2001 From: Klaus Loeffelmann Date: Sat, 13 Jun 2026 13:38:11 -0700 Subject: [PATCH 03/69] Add Visual Styles (.NET 11): VisualStylesMode, animation timer, modern Button and CheckBox toggle renderers Introduces the (non-experimental) Visual Styles versioning API and the first modern renderers gated behind it: - VisualStylesMode enum (Classic/Disabled/Net11/Latest); ambient Control.VisualStylesMode (+event/On-methods); Application.DefaultVisualStylesMode/SetDefaultVisualStylesMode; Appearance.ToggleSwitch; VB framework APIs. - HighPrecisionTimer (internal, Primitives) as the animation frame trigger, with tests. - AnimationManager/AnimatedControlRenderer driven by HighPrecisionTimer. - Conservative dark-mode Standard button (owner-drawn, reachable) + modern WinUI-style Button renderer. - CheckBox Appearance.ToggleSwitch modern toggle switch (animated, flicker-free). - WinformsControlsTest VisualStylesButtons exploratory harness; unit tests. Verified CI-clean with build.cmd: System.Windows.Forms, Microsoft.VisualBasic.Forms and Primitives build with no analyzer/PublicAPI/style errors (the only remaining failure is the pre-existing BuildAssist/AxHosts step, which is an environment limitation unrelated to these changes). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../ApplyApplicationDefaultsEventArgs.vb | 6 + .../WindowsFormsApplicationBase.vb | 25 +- .../src/PublicAPI.Unshipped.txt | 4 + .../Forms/Animation/HighPrecisionTimer.cs | 330 ++++++++++++++++++ .../Forms/Animation/HighPrecisionTimerTick.cs | 30 ++ .../Animation/HighPrecisionTimerTests.cs | 220 ++++++++++++ .../PublicAPI.Unshipped.txt | 19 + src/System.Windows.Forms/Resources/SR.resx | 9 + .../Resources/xlf/SR.cs.xlf | 15 + .../Resources/xlf/SR.de.xlf | 15 + .../Resources/xlf/SR.es.xlf | 15 + .../Resources/xlf/SR.fr.xlf | 15 + .../Resources/xlf/SR.it.xlf | 15 + .../Resources/xlf/SR.ja.xlf | 15 + .../Resources/xlf/SR.ko.xlf | 15 + .../Resources/xlf/SR.pl.xlf | 15 + .../Resources/xlf/SR.pt-BR.xlf | 15 + .../Resources/xlf/SR.ru.xlf | 15 + .../Resources/xlf/SR.tr.xlf | 15 + .../Resources/xlf/SR.zh-Hans.xlf | 15 + .../Resources/xlf/SR.zh-Hant.xlf | 15 + .../System/Windows/Forms/Application.cs | 57 +++ .../System/Windows/Forms/Control.cs | 140 ++++++++ .../Forms/Controls/Buttons/Appearance.cs | 13 +- .../Windows/Forms/Controls/Buttons/Button.cs | 34 -- .../Forms/Controls/Buttons/ButtonBase.cs | 16 + .../DarkMode/ButtonDarkModeAdapter.cs | 14 +- .../DarkMode/ButtonDarkModeRendererBase.cs | 11 + .../DarkMode/DarkModeAdapterFactory.cs | 13 +- .../DarkMode/ModernButtonDarkModeRenderer.cs | 199 +++++++++++ .../Forms/Controls/Buttons/CheckBox.cs | 100 +++++- .../Forms/Controls/TextBox/TextBoxBase.cs | 11 +- .../Animation/AnimatedControlRenderer.cs | 152 ++++++++ .../Rendering/Animation/AnimationCycle.cs | 11 + .../AnimationManager.AnimationRendererItem.cs | 25 ++ .../Rendering/Animation/AnimationManager.cs | 154 ++++++++ .../CheckBox/AnimatedToggleSwitchRenderer.cs | 140 ++++++++ .../Rendering/CheckBox/ModernCheckBoxStyle.cs | 10 + .../System/Windows/Forms/VisualStylesMode.cs | 41 +++ .../WinformsControlsTest/Buttons.cs | 8 + .../VisualStylesButtons.cs | 193 ++++++++++ .../Forms/AnimatedControlRendererTests.cs | 89 +++++ .../Windows/Forms/ButtonVisualStylesTests.cs | 76 ++++ .../Forms/CheckBoxToggleSwitchTests.cs | 84 +++++ .../Forms/ControlTests.VisualStylesMode.cs | 143 ++++++++ 45 files changed, 2525 insertions(+), 47 deletions(-) create mode 100644 src/System.Windows.Forms.Primitives/src/System/Windows/Forms/Animation/HighPrecisionTimer.cs create mode 100644 src/System.Windows.Forms.Primitives/src/System/Windows/Forms/Animation/HighPrecisionTimerTick.cs create mode 100644 src/System.Windows.Forms.Primitives/tests/UnitTests/System/Windows/Forms/Animation/HighPrecisionTimerTests.cs create mode 100644 src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ModernButtonDarkModeRenderer.cs create mode 100644 src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimatedControlRenderer.cs create mode 100644 src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationCycle.cs create mode 100644 src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationManager.AnimationRendererItem.cs create mode 100644 src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationManager.cs create mode 100644 src/System.Windows.Forms/System/Windows/Forms/Rendering/CheckBox/AnimatedToggleSwitchRenderer.cs create mode 100644 src/System.Windows.Forms/System/Windows/Forms/Rendering/CheckBox/ModernCheckBoxStyle.cs create mode 100644 src/System.Windows.Forms/System/Windows/Forms/VisualStylesMode.cs create mode 100644 src/test/integration/WinformsControlsTest/VisualStylesButtons.cs create mode 100644 src/test/unit/System.Windows.Forms/System/Windows/Forms/AnimatedControlRendererTests.cs create mode 100644 src/test/unit/System.Windows.Forms/System/Windows/Forms/ButtonVisualStylesTests.cs create mode 100644 src/test/unit/System.Windows.Forms/System/Windows/Forms/CheckBoxToggleSwitchTests.cs create mode 100644 src/test/unit/System.Windows.Forms/System/Windows/Forms/ControlTests.VisualStylesMode.cs diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/ApplyApplicationDefaultsEventArgs.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/ApplyApplicationDefaultsEventArgs.vb index 91ea19640da..aebcd29b546 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/ApplyApplicationDefaultsEventArgs.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/ApplyApplicationDefaultsEventArgs.vb @@ -32,6 +32,12 @@ Namespace Microsoft.VisualBasic.ApplicationServices ''' Public Property ColorMode As SystemColorMode + ''' + ''' Setting this property inside the event handler determines the + ''' for the application. + ''' + Public Property VisualStylesMode As VisualStylesMode + ''' ''' Setting this property inside the event handler causes a ''' new default for Forms and UserControls to be set. diff --git a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/WindowsFormsApplicationBase.vb b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/WindowsFormsApplicationBase.vb index 6e14d471534..f29d8a4816e 100644 --- a/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/WindowsFormsApplicationBase.vb +++ b/src/Microsoft.VisualBasic.Forms/src/Microsoft/VisualBasic/ApplicationServices/WindowsFormsApplicationBase.vb @@ -69,6 +69,9 @@ Namespace Microsoft.VisualBasic.ApplicationServices ' Note: We aim to expose this to the App Designer in later runtime/VS versions. Private _colorMode As SystemColorMode = SystemColorMode.Classic + ' The VisualStylesMode (renderer version) the user assigned to the ApplyApplicationDefaults event. + Private _visualStylesMode As VisualStylesMode = VisualStylesMode.Classic + ' We only need to show the splash screen once. ' Protect the user from himself if they are overriding our app model. Private _didSplashScreen As Boolean @@ -200,6 +203,22 @@ Namespace Microsoft.VisualBasic.ApplicationServices End Set End Property + ''' + ''' Gets or sets the (renderer version) for the application. + ''' + ''' + ''' The that the application uses to render its controls. + ''' + + Protected Property VisualStylesMode As VisualStylesMode + Get + Return _visualStylesMode + End Get + Set(value As VisualStylesMode) + _visualStylesMode = value + End Set + End Property + ''' ''' Determines whether this application will use the XP Windows styles for windows, controls, etc. ''' @@ -748,7 +767,8 @@ Namespace Microsoft.VisualBasic.ApplicationServices HighDpiMode, ColorMode) With { - .MinimumSplashScreenDisplayTime = MinimumSplashScreenDisplayTime + .MinimumSplashScreenDisplayTime = MinimumSplashScreenDisplayTime, + .VisualStylesMode = VisualStylesMode } RaiseEvent ApplyApplicationDefaults(Me, applicationDefaultsEventArgs) @@ -765,6 +785,7 @@ Namespace Microsoft.VisualBasic.ApplicationServices _highDpiMode = applicationDefaultsEventArgs.HighDpiMode _colorMode = applicationDefaultsEventArgs.ColorMode + _visualStylesMode = applicationDefaultsEventArgs.VisualStylesMode ' Then, it's applying what we got back as HighDpiMode. Dim dpiSetResult As Boolean = Application.SetHighDpiMode(_highDpiMode) @@ -780,6 +801,8 @@ Namespace Microsoft.VisualBasic.ApplicationServices Application.EnableVisualStyles() End If + Application.SetDefaultVisualStylesMode(_visualStylesMode) + Application.SetColorMode(_colorMode) ' We'll handle "/nosplash" for you. diff --git a/src/Microsoft.VisualBasic.Forms/src/PublicAPI.Unshipped.txt b/src/Microsoft.VisualBasic.Forms/src/PublicAPI.Unshipped.txt index e69de29bb2d..31142494a9b 100644 --- a/src/Microsoft.VisualBasic.Forms/src/PublicAPI.Unshipped.txt +++ b/src/Microsoft.VisualBasic.Forms/src/PublicAPI.Unshipped.txt @@ -0,0 +1,4 @@ +Microsoft.VisualBasic.ApplicationServices.ApplyApplicationDefaultsEventArgs.VisualStylesMode() -> System.Windows.Forms.VisualStylesMode +Microsoft.VisualBasic.ApplicationServices.ApplyApplicationDefaultsEventArgs.VisualStylesMode(AutoPropertyValue As System.Windows.Forms.VisualStylesMode) -> Void +Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.VisualStylesMode() -> System.Windows.Forms.VisualStylesMode +Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.VisualStylesMode(value As System.Windows.Forms.VisualStylesMode) -> Void diff --git a/src/System.Windows.Forms.Primitives/src/System/Windows/Forms/Animation/HighPrecisionTimer.cs b/src/System.Windows.Forms.Primitives/src/System/Windows/Forms/Animation/HighPrecisionTimer.cs new file mode 100644 index 00000000000..9c6b1bb7cca --- /dev/null +++ b/src/System.Windows.Forms.Primitives/src/System/Windows/Forms/Animation/HighPrecisionTimer.cs @@ -0,0 +1,330 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +namespace System.Windows.Forms.Animation; + +/// +/// A high-precision static timer designed to trigger WinForms control animations +/// at 60 Hz (or 30 Hz on systems without high-resolution timer support). +/// Controls register callbacks that are marshalled back to the UI thread via +/// the captured . +/// +internal static partial class HighPrecisionTimer +{ + // Target frame intervals. + private const double TargetFrameTimeMs60Hz = 16.667; + private const double TargetFrameTimeMs30Hz = 33.333; + + // We aim the PeriodicTimer earlier than the target frame time to allow + // for spin-wait refinement to hit the target precisely. + private const double TimerTickMs60Hz = 14.0; + private const double TimerTickMs30Hz = 30.0; + + // Maximum drift before we assert (20% of target frame time sustained over 10 frames). + private const int MaxDriftFrames = 10; + private const double MaxDriftThresholdRatio = 0.20; + + private static readonly Lock s_lock = new(); + private static readonly ConcurrentDictionary s_registrations = new(); + private static long s_nextId; + private static CancellationTokenSource? s_cts; + private static Task? s_loopTask; + private static bool s_highResolutionAvailable; + private static double s_targetFrameTimeMs; + private static double s_timerTickMs; + + /// + /// Gets the current target frame time in milliseconds. + /// + internal static double TargetFrameTimeMs => s_targetFrameTimeMs; + + /// + /// Gets whether high-resolution timing (60 Hz) is available on this system. + /// + internal static bool IsHighResolutionAvailable => s_highResolutionAvailable; + + /// + /// Registers a callback to be invoked on each animation frame tick. + /// The current is captured and used + /// to marshal the callback to the appropriate thread. + /// + /// + /// The async callback invoked each frame. Receives timing information and a cancellation token. + /// + /// A that must be disposed to unregister. + /// + /// Thrown when no is available on the current thread. + /// + internal static TimerRegistration Register(Func callback) + { + ArgumentNullException.ThrowIfNull(callback); + + SynchronizationContext? syncContext = SynchronizationContext.Current + ?? throw new InvalidOperationException( + "A SynchronizationContext must be available on the calling thread. " + + "Ensure registration is performed from a UI thread."); + + long id = Interlocked.Increment(ref s_nextId); + Registration registration = new(id, callback, syncContext); + s_registrations.TryAdd(id, registration); + + EnsureRunning(); + + return new TimerRegistration(id); + } + + /// + /// Unregisters a previously registered callback. + /// + internal static void Unregister(long registrationId) + { + s_registrations.TryRemove(registrationId, out _); + + if (s_registrations.IsEmpty) + { + StopTimer(); + } + } + + private static void EnsureRunning() + { + lock (s_lock) + { + if (s_loopTask is not null) + { + return; + } + + s_highResolutionAvailable = TrySetHighResolutionTimerMode(); + s_targetFrameTimeMs = s_highResolutionAvailable ? TargetFrameTimeMs60Hz : TargetFrameTimeMs30Hz; + s_timerTickMs = s_highResolutionAvailable ? TimerTickMs60Hz : TimerTickMs30Hz; + + s_cts = new CancellationTokenSource(); + CancellationToken cancellationToken = s_cts.Token; + s_loopTask = Task.Factory.StartNew( + () => TimerLoopAsync(cancellationToken), + cancellationToken, + TaskCreationOptions.LongRunning, + TaskScheduler.Default).Unwrap(); + } + } + + private static void StopTimer() + { + CancellationTokenSource? cts; + + lock (s_lock) + { + cts = s_cts; + s_cts = null; + s_loopTask = null; + } + + if (cts is not null) + { + cts.Cancel(); + cts.Dispose(); + } + + // Best-effort: restore timer resolution. + if (s_highResolutionAvailable) + { + ResetTimerResolution(); + } + } + + private static async Task TimerLoopAsync(CancellationToken cancellationToken) + { + using PeriodicTimer periodicTimer = new(TimeSpan.FromMilliseconds(s_timerTickMs)); + Stopwatch stopwatch = Stopwatch.StartNew(); + long lastTickTimestamp = 0; + int consecutiveDriftFrames = 0; + + try + { + while (await periodicTimer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false)) + { + // Spin-wait refinement: if we woke up early, spin until target time. + double targetMs = lastTickTimestamp + s_targetFrameTimeMs; + SpinToTarget(stopwatch, targetMs); + + long currentTimestamp = stopwatch.ElapsedMilliseconds; + double elapsed = currentTimestamp - lastTickTimestamp; + + // Drift detection: check if we are consistently overshooting. + double drift = elapsed - s_targetFrameTimeMs; + if (Math.Abs(drift) > s_targetFrameTimeMs * MaxDriftThresholdRatio) + { + consecutiveDriftFrames++; + Debug.Assert( + consecutiveDriftFrames < MaxDriftFrames, + $"HighPrecisionTimer: Excessive drift detected. " + + $"Drift: {drift:F2}ms over {consecutiveDriftFrames} consecutive frames."); + } + else + { + consecutiveDriftFrames = 0; + } + + lastTickTimestamp = currentTimestamp; + + // Dispatch to all registered callbacks. + DispatchCallbacks( + TimeSpan.FromMilliseconds(currentTimestamp), + TimeSpan.FromMilliseconds(elapsed), + cancellationToken); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // Normal shutdown. + } + } + + private static void SpinToTarget(Stopwatch stopwatch, double targetMs) + { + SpinWait spinner = default; + + while (stopwatch.Elapsed.TotalMilliseconds < targetMs) + { + // SpinOnce with sleep1Threshold=-1 ensures we stay in PAUSE/yield + // mode and never escalate to Thread.Sleep(1). + spinner.SpinOnce(sleep1Threshold: -1); + } + } + + private static void DispatchCallbacks( + TimeSpan timestamp, + TimeSpan elapsed, + CancellationToken cancellationToken) + { + foreach (KeyValuePair kvp in s_registrations) + { + Registration registration = kvp.Value; + + // Skip if previous callback is still in flight (frame coalescing). + if (Interlocked.CompareExchange(ref registration.InFlight, 1, 0) != 0) + { + Interlocked.Increment(ref registration.DroppedFrames); + continue; + } + + long frameIndex = Interlocked.Increment(ref registration.FrameIndex) - 1; + int dropped = Interlocked.Exchange(ref registration.DroppedFrames, 0); + + HighPrecisionTimerTick tick = new() + { + Timestamp = timestamp, + Elapsed = elapsed, + DroppedFrames = dropped, + FrameIndex = frameIndex + }; + + registration.SyncContext.Post( + _ => _ = InvokeCallbackAsync(registration, tick, cancellationToken), + null); + } + } + + private static async Task InvokeCallbackAsync( + Registration registration, + HighPrecisionTimerTick tick, + CancellationToken cancellationToken) + { + try + { + await registration.Callback(tick, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Debug.Fail($"HighPrecisionTimer: Unhandled exception in callback: {ex.Message}"); + } + finally + { + Interlocked.Exchange(ref registration.InFlight, 0); + } + } + + [SupportedOSPlatform("windows10.0.17134.0")] + private static bool TrySetHighResolutionTimerMode() + { + if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134)) + { + return false; + } + + try + { + // Use timeBeginPeriod for documented, reliable high-resolution timing. + return NativeMethods.TimeBeginPeriod(1) == 0; // TIMERR_NOERROR + } + catch (Exception ex) when (!ex.IsCriticalException()) + { + return false; + } + } + + private static void ResetTimerResolution() + { + try + { + NativeMethods.TimeEndPeriod(1); + } + catch (Exception ex) when (!ex.IsCriticalException()) + { + // Best effort. + } + } + + private static partial class NativeMethods + { + [LibraryImport("winmm.dll")] + internal static partial int TimeBeginPeriod(int uPeriod); + + [LibraryImport("winmm.dll")] + internal static partial int TimeEndPeriod(int uPeriod); + } + + private sealed class Registration( + long id, + Func callback, + SynchronizationContext syncContext) + { + public long Id { get; } = id; + public Func Callback { get; } = callback; + public SynchronizationContext SyncContext { get; } = syncContext; + public int InFlight; + public int DroppedFrames; + public long FrameIndex; + } + + /// + /// Represents a timer registration. Dispose to unregister. + /// + internal readonly struct TimerRegistration : IDisposable + { + private readonly long _id; + + internal TimerRegistration(long id) => _id = id; + + /// Gets the registration identifier. + public long Id => _id; + + /// Unregisters this callback from the timer. + public void Dispose() => Unregister(_id); + } + + /// + /// Resets internal state. For testing purposes only. + /// + internal static void Reset() + { + StopTimer(); + s_registrations.Clear(); + s_nextId = 0; + } +} diff --git a/src/System.Windows.Forms.Primitives/src/System/Windows/Forms/Animation/HighPrecisionTimerTick.cs b/src/System.Windows.Forms.Primitives/src/System/Windows/Forms/Animation/HighPrecisionTimerTick.cs new file mode 100644 index 00000000000..3b6557e2643 --- /dev/null +++ b/src/System.Windows.Forms.Primitives/src/System/Windows/Forms/Animation/HighPrecisionTimerTick.cs @@ -0,0 +1,30 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace System.Windows.Forms.Animation; + +/// +/// Provides timing information for a single animation frame tick. +/// +internal readonly struct HighPrecisionTimerTick +{ + /// + /// The absolute timestamp of this tick from the timer's epoch. + /// + public TimeSpan Timestamp { get; init; } + + /// + /// The elapsed time since the last tick delivered to this registration. + /// + public TimeSpan Elapsed { get; init; } + + /// + /// The number of frames that were dropped (coalesced) since the last delivered tick. + /// + public int DroppedFrames { get; init; } + + /// + /// The zero-based frame index for this registration. + /// + public long FrameIndex { get; init; } +} diff --git a/src/System.Windows.Forms.Primitives/tests/UnitTests/System/Windows/Forms/Animation/HighPrecisionTimerTests.cs b/src/System.Windows.Forms.Primitives/tests/UnitTests/System/Windows/Forms/Animation/HighPrecisionTimerTests.cs new file mode 100644 index 00000000000..b577b820494 --- /dev/null +++ b/src/System.Windows.Forms.Primitives/tests/UnitTests/System/Windows/Forms/Animation/HighPrecisionTimerTests.cs @@ -0,0 +1,220 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Windows.Forms.Animation; + +namespace System.Windows.Forms.Primitives.Tests.Animation; + +/// +/// A test synchronization context that executes posted callbacks immediately +/// on the thread pool, simulating a UI message pump for testing purposes. +/// +internal sealed class TestSynchronizationContext : SynchronizationContext +{ + public override void Post(SendOrPostCallback d, object? state) => ThreadPool.QueueUserWorkItem(_ => d(state)); + + public override void Send(SendOrPostCallback d, object? state) => d(state); +} + +// The timer is process-wide static; disable parallelization so timing-sensitive +// assertions are not perturbed by concurrently running tests. +[Collection(nameof(HighPrecisionTimerTests))] +[CollectionDefinition(nameof(HighPrecisionTimerTests), DisableParallelization = true)] +public sealed class HighPrecisionTimerTests : IDisposable +{ + private readonly SynchronizationContext? _originalContext; + + public HighPrecisionTimerTests() + { + _originalContext = SynchronizationContext.Current; + SynchronizationContext.SetSynchronizationContext(new TestSynchronizationContext()); + } + + public void Dispose() + { + HighPrecisionTimer.Reset(); + SynchronizationContext.SetSynchronizationContext(_originalContext); + } + + [Fact] + public async Task SingleConsumer_ReceivesTicksAtApproximatelyExpectedRate() + { + ConcurrentBag intervals = []; + Stopwatch stopwatch = Stopwatch.StartNew(); + double lastTick = 0; + int tickCount = 0; + const int TargetTicks = 30; + + using HighPrecisionTimer.TimerRegistration registration = HighPrecisionTimer.Register( + (tick, ct) => + { + double now = stopwatch.Elapsed.TotalMilliseconds; + if (lastTick > 0) + { + intervals.Add(now - lastTick); + } + + lastTick = now; + Interlocked.Increment(ref tickCount); + return ValueTask.CompletedTask; + }); + + await WaitForAsync(() => tickCount >= TargetTicks); + + List sorted = [.. intervals.OrderBy(x => x)]; + double targetMs = HighPrecisionTimer.TargetFrameTimeMs; + + // Relaxed bounds to remain robust on loaded CI machines: the median must be in a + // sane band around the target frame time. + double median = Percentile(sorted, 0.50); + median.Should().BeLessThan(targetMs * 3.0, "the median frame interval should stay near the target"); + } + + [Fact] + public async Task MultipleConsumers_AllReceiveTicksIndependently() + { + const int ConsumerCount = 5; + const int TargetTicks = 15; + int[] tickCounts = new int[ConsumerCount]; + HighPrecisionTimer.TimerRegistration[] registrations = new HighPrecisionTimer.TimerRegistration[ConsumerCount]; + + for (int i = 0; i < ConsumerCount; i++) + { + int index = i; + registrations[i] = HighPrecisionTimer.Register( + (tick, ct) => + { + Interlocked.Increment(ref tickCounts[index]); + return ValueTask.CompletedTask; + }); + } + + await WaitForAsync(() => tickCounts.Min() >= TargetTicks); + + foreach (HighPrecisionTimer.TimerRegistration registration in registrations) + { + registration.Dispose(); + } + + tickCounts.Should().OnlyContain(count => count >= TargetTicks); + } + + [Fact] + public async Task SlowConsumer_DropsFramesInsteadOfQueuing() + { + ConcurrentBag ticks = []; + + using HighPrecisionTimer.TimerRegistration registration = HighPrecisionTimer.Register( + async (tick, ct) => + { + ticks.Add(tick); + // Simulate slow rendering (well over one frame time). + await Task.Delay((int)(HighPrecisionTimer.TargetFrameTimeMs * 3), ct); + }); + + await WaitForAsync(() => ticks.Sum(t => t.DroppedFrames) > 0, timeoutMs: 4000); + + ticks.Sum(t => t.DroppedFrames).Should().BeGreaterThan(0, "a slow consumer should report dropped frames"); + } + + [Fact] + public async Task Registration_Disposal_StopsCallbacks() + { + int tickCount = 0; + + HighPrecisionTimer.TimerRegistration registration = HighPrecisionTimer.Register( + (tick, ct) => + { + Interlocked.Increment(ref tickCount); + return ValueTask.CompletedTask; + }); + + await WaitForAsync(() => tickCount > 0); + registration.Dispose(); + int ticksAfterDispose = Volatile.Read(ref tickCount); + + await Task.Delay(200, TestContext.Current.CancellationToken); + + // At most a couple of in-flight callbacks may land right after disposal. + (Volatile.Read(ref tickCount) - ticksAfterDispose).Should().BeLessThanOrEqualTo(2); + } + + [Fact] + public void Registration_WithoutSyncContext_Throws() + { + SynchronizationContext? original = SynchronizationContext.Current; + SynchronizationContext.SetSynchronizationContext(null); + + try + { + Action act = () => HighPrecisionTimer.Register((tick, ct) => ValueTask.CompletedTask); + act.Should().Throw(); + } + finally + { + SynchronizationContext.SetSynchronizationContext(original); + } + } + + [Fact] + public async Task TimerTick_ProvidesElapsedAndIncreasingFrameIndex() + { + ConcurrentBag elapsedValues = []; + long lastFrameIndex = -1; + bool frameIndexMonotonic = true; + int tickCount = 0; + const int TargetTicks = 15; + + using HighPrecisionTimer.TimerRegistration registration = HighPrecisionTimer.Register( + (tick, ct) => + { + if (tick.FrameIndex <= lastFrameIndex) + { + frameIndexMonotonic = false; + } + + lastFrameIndex = tick.FrameIndex; + + if (tick.FrameIndex > 0) + { + elapsedValues.Add(tick.Elapsed.TotalMilliseconds); + } + + Interlocked.Increment(ref tickCount); + return ValueTask.CompletedTask; + }); + + await WaitForAsync(() => tickCount >= TargetTicks); + + frameIndexMonotonic.Should().BeTrue("frame indices should increase monotonically"); + elapsedValues.Should().NotBeEmpty(); + elapsedValues.Should().OnlyContain(value => value > 0, "elapsed time between ticks should be positive"); + } + + private static double Percentile(List sortedValues, double percentile) + { + if (sortedValues.Count == 0) + { + return 0; + } + + int index = (int)Math.Ceiling(percentile * sortedValues.Count) - 1; + return sortedValues[Math.Max(0, index)]; + } + + private static async Task WaitForAsync(Func condition, int timeoutMs = 5000) + { + Stopwatch stopwatch = Stopwatch.StartNew(); + while (!condition()) + { + if (stopwatch.ElapsedMilliseconds > timeoutMs) + { + throw new TimeoutException("Timed out waiting for the expected timer ticks."); + } + + await Task.Delay(25, TestContext.Current.CancellationToken); + } + } +} diff --git a/src/System.Windows.Forms/PublicAPI.Unshipped.txt b/src/System.Windows.Forms/PublicAPI.Unshipped.txt index e69de29bb2d..aa75c9962cb 100644 --- a/src/System.Windows.Forms/PublicAPI.Unshipped.txt +++ b/src/System.Windows.Forms/PublicAPI.Unshipped.txt @@ -0,0 +1,19 @@ +#nullable enable +override System.Windows.Forms.ButtonBase.OnVisualStylesModeChanged(System.EventArgs! e) -> void +override System.Windows.Forms.CheckBox.Dispose(bool disposing) -> void +override System.Windows.Forms.CheckBox.OnPaint(System.Windows.Forms.PaintEventArgs! pevent) -> void +override System.Windows.Forms.CheckBox.OnVisualStylesModeChanged(System.EventArgs! e) -> void +static System.Windows.Forms.Application.DefaultVisualStylesMode.get -> System.Windows.Forms.VisualStylesMode +static System.Windows.Forms.Application.SetDefaultVisualStylesMode(System.Windows.Forms.VisualStylesMode styleSetting) -> void +System.Windows.Forms.Appearance.ToggleSwitch = 2 -> System.Windows.Forms.Appearance +System.Windows.Forms.Control.VisualStylesMode.get -> System.Windows.Forms.VisualStylesMode +System.Windows.Forms.Control.VisualStylesMode.set -> void +System.Windows.Forms.Control.VisualStylesModeChanged -> System.EventHandler? +System.Windows.Forms.VisualStylesMode +System.Windows.Forms.VisualStylesMode.Classic = 0 -> System.Windows.Forms.VisualStylesMode +System.Windows.Forms.VisualStylesMode.Disabled = 1 -> System.Windows.Forms.VisualStylesMode +System.Windows.Forms.VisualStylesMode.Latest = 32767 -> System.Windows.Forms.VisualStylesMode +System.Windows.Forms.VisualStylesMode.Net11 = 2 -> System.Windows.Forms.VisualStylesMode +virtual System.Windows.Forms.Control.DefaultVisualStylesMode.get -> System.Windows.Forms.VisualStylesMode +virtual System.Windows.Forms.Control.OnParentVisualStylesModeChanged(System.EventArgs! e) -> void +virtual System.Windows.Forms.Control.OnVisualStylesModeChanged(System.EventArgs! e) -> void diff --git a/src/System.Windows.Forms/Resources/SR.resx b/src/System.Windows.Forms/Resources/SR.resx index 53d5073b748..168cb5ba2ae 100644 --- a/src/System.Windows.Forms/Resources/SR.resx +++ b/src/System.Windows.Forms/Resources/SR.resx @@ -171,6 +171,9 @@ Application exception mode cannot be changed once any Controls are created in the application. + + The default visual styles mode can only be set once and cannot be changed afterwards. + &Apply @@ -6931,6 +6934,12 @@ Stack trace where the illegal operation occurred was: Occurs when the value of the DataContext property changes. + + Determines how the control renders itself when visual styles are applied. + + + Occurs when the value of the VisualStylesMode property changes. + Gets or sets the parameter that is passed to the Command property's object on execution or on execution context request. diff --git a/src/System.Windows.Forms/Resources/xlf/SR.cs.xlf b/src/System.Windows.Forms/Resources/xlf/SR.cs.xlf index ce2bc9260f9..a4decd0c852 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.cs.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.cs.xlf @@ -242,6 +242,11 @@ Režim výjimky vlákna nelze změnit po vytvoření ovládacích prvků ve vlákně. + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply &Použít @@ -2172,6 +2177,16 @@ Určuje, zda je ovládací prvek viditelný nebo skrytý. + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. Šířka ovládacího prvku, v souřadnicích kontejneru. diff --git a/src/System.Windows.Forms/Resources/xlf/SR.de.xlf b/src/System.Windows.Forms/Resources/xlf/SR.de.xlf index b5cf47b1170..7236f7cccdf 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.de.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.de.xlf @@ -242,6 +242,11 @@ Der Threadausnahmemodus kann nicht mehr geändert werden, sobald Steuerelemente in dem Thread erstellt wurden. + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply &Anwenden @@ -2172,6 +2177,16 @@ Bestimmt, ob das Steuerelement sichtbar oder ausgeblendet ist. + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. Die Breite des Steuerelements (in Containerkoordinaten). diff --git a/src/System.Windows.Forms/Resources/xlf/SR.es.xlf b/src/System.Windows.Forms/Resources/xlf/SR.es.xlf index 82eb0cd40bb..f8a1528ce7d 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.es.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.es.xlf @@ -242,6 +242,11 @@ El modo de excepción del subproceso no se puede cambiar una vez que se creen Controles en el subproceso. + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply &Aplicar @@ -2172,6 +2177,16 @@ Determina si el control está visible u oculto. + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. Ancho del control, en las coordenadas del contenedor. diff --git a/src/System.Windows.Forms/Resources/xlf/SR.fr.xlf b/src/System.Windows.Forms/Resources/xlf/SR.fr.xlf index f02c36b8e65..772318b29b4 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.fr.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.fr.xlf @@ -242,6 +242,11 @@ Impossible de modifier le mode d'exceptions du thread une fois que des Controls ont été créés sur le thread. + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply &Appliquer @@ -2172,6 +2177,16 @@ Détermine si le contrôle est visible ou masqué. + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. La largeur du contrôle, en coordonnées conteneur. diff --git a/src/System.Windows.Forms/Resources/xlf/SR.it.xlf b/src/System.Windows.Forms/Resources/xlf/SR.it.xlf index fc9f709a0be..8e75e890990 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.it.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.it.xlf @@ -242,6 +242,11 @@ Una volta creati controlli nel thread, non è possibile modificare la modalità eccezioni del thread. + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply &Applica @@ -2172,6 +2177,16 @@ Determina se il controllo è visibile o nascosto. + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. La larghezza del controllo, nelle coordinate del contenitore. diff --git a/src/System.Windows.Forms/Resources/xlf/SR.ja.xlf b/src/System.Windows.Forms/Resources/xlf/SR.ja.xlf index 4511ba6cf76..91ca033cf05 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.ja.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.ja.xlf @@ -242,6 +242,11 @@ スレッドでコントロールが作成された後、スレッド例外モードを変更することはできません。 + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply 適用(&A) @@ -2172,6 +2177,16 @@ コントロールの表示、非表示を示します。 + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. コンテナー座標で表したコントロールの幅です。 diff --git a/src/System.Windows.Forms/Resources/xlf/SR.ko.xlf b/src/System.Windows.Forms/Resources/xlf/SR.ko.xlf index 2924f72aab7..612beb8b44f 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.ko.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.ko.xlf @@ -242,6 +242,11 @@ 스레드에서 컨트롤이 만들어진 이후에는 스레드 예외 모드를 변경할 수 없습니다. + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply 적용(&A) @@ -2172,6 +2177,16 @@ 컨트롤을 표시할지 여부를 결정합니다. + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. 컨테이너 좌표로 표시한 컨트롤의 너비입니다. diff --git a/src/System.Windows.Forms/Resources/xlf/SR.pl.xlf b/src/System.Windows.Forms/Resources/xlf/SR.pl.xlf index f86297cb7f6..ea628ae265e 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.pl.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.pl.xlf @@ -242,6 +242,11 @@ Trybu wyjątków wątku nie można zmienić po utworzeniu jakichkolwiek formantów w aplikacji. + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply &Zastosuj @@ -2172,6 +2177,16 @@ Określa, czy formant jest widoczny, czy ukryty. + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. Szerokość formantu we współrzędnych kontenera. diff --git a/src/System.Windows.Forms/Resources/xlf/SR.pt-BR.xlf b/src/System.Windows.Forms/Resources/xlf/SR.pt-BR.xlf index 5dcda8ac793..c550a374866 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.pt-BR.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.pt-BR.xlf @@ -242,6 +242,11 @@ Não é possível alterar o modo de exceção de thread após a criação de qualquer controle no thread. + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply &Aplicar @@ -2172,6 +2177,16 @@ Determina se o controle está visível ou oculto. + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. A largura do controle, nas coordenadas do recipiente. diff --git a/src/System.Windows.Forms/Resources/xlf/SR.ru.xlf b/src/System.Windows.Forms/Resources/xlf/SR.ru.xlf index 89af4e75583..5cc2555a79c 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.ru.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.ru.xlf @@ -242,6 +242,11 @@ Режим исключений потоков нельзя изменить, если в потоке были созданы элементы управления. + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply &Применить @@ -2172,6 +2177,16 @@ Определяет, отображается или скрыт данный элемент управления. + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. Ширина элемента управления в координатах контейнера. diff --git a/src/System.Windows.Forms/Resources/xlf/SR.tr.xlf b/src/System.Windows.Forms/Resources/xlf/SR.tr.xlf index 9e72305a890..d14fe6ca79c 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.tr.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.tr.xlf @@ -242,6 +242,11 @@ İş parçacığında herhangi bir Denetim oluşturulduktan sonra iş parçacığı özel durum modu değiştirilemez. + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply &Uygula @@ -2172,6 +2177,16 @@ Denetimin görünür mü yoksa gizli mi olduğunu belirler. + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. Denetimin genişliği (kapsayıcı koordinatlarında). diff --git a/src/System.Windows.Forms/Resources/xlf/SR.zh-Hans.xlf b/src/System.Windows.Forms/Resources/xlf/SR.zh-Hans.xlf index 6827f20269f..c4c47d14f36 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.zh-Hans.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.zh-Hans.xlf @@ -242,6 +242,11 @@ 只要在线程上创建了任何控件,则线程异常模式将不能再有任何更改。 + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply 应用(&A) @@ -2172,6 +2177,16 @@ 确定该控件是可见的还是隐藏的。 + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. 控件的宽度(以容器坐标表示)。 diff --git a/src/System.Windows.Forms/Resources/xlf/SR.zh-Hant.xlf b/src/System.Windows.Forms/Resources/xlf/SR.zh-Hant.xlf index 15f5f06c126..a87ab568b67 100644 --- a/src/System.Windows.Forms/Resources/xlf/SR.zh-Hant.xlf +++ b/src/System.Windows.Forms/Resources/xlf/SR.zh-Hant.xlf @@ -242,6 +242,11 @@ 一旦在執行緒上建立了控制項,就不能變更執行緒例外狀況模式。 + + The default visual styles mode can only be set once and cannot be changed afterwards. + The default visual styles mode can only be set once and cannot be changed afterwards. + + &Apply 套用(&A) @@ -2172,6 +2177,16 @@ 決定控制項是可見或隱藏。 + + Occurs when the value of the VisualStylesMode property changes. + Occurs when the value of the VisualStylesMode property changes. + + + + Determines how the control renders itself when visual styles are applied. + Determines how the control renders itself when visual styles are applied. + + The width of the control, in container coordinates. 容器座標中控制項的寬度。 diff --git a/src/System.Windows.Forms/System/Windows/Forms/Application.cs b/src/System.Windows.Forms/System/Windows/Forms/Application.cs index aab496c2744..08c6e7349fa 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Application.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Application.cs @@ -45,6 +45,8 @@ public sealed partial class Application private static SystemColorMode? s_colorMode; + private static VisualStylesMode? s_defaultVisualStylesMode; + private const string DarkModeKeyPath = "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; private const string DarkModeKey = "AppsUseLightTheme"; private const int SystemDarkModeDisabled = 1; @@ -592,6 +594,54 @@ public static void RegisterMessageLoop(MessageLoopCallback? callback) public static bool RenderWithVisualStyles => ComCtlSupportsVisualStyles && VisualStyleRenderer.IsSupported; + /// + /// Gets the default used as the rendering style guideline for the + /// application's controls. + /// + /// + /// The used as the rendering style guideline for the application's + /// controls. This is when visual styles are enabled and + /// otherwise, unless it has been changed by a call to + /// . + /// + /// + /// + /// The default value is so that applications that simply + /// recompile against a newer framework keep their existing look. Opt in to a newer renderer by + /// calling . + /// + /// + public static VisualStylesMode DefaultVisualStylesMode + => s_defaultVisualStylesMode ??= + UseVisualStyles ? VisualStylesMode.Classic : VisualStylesMode.Disabled; + + /// + /// Sets the default used as the rendering style guideline for the + /// application's controls. + /// + /// The version of the visual styles renderer to use by default. + /// + /// The default visual styles mode has already been set to a different value. It can only be set once. + /// + /// + /// + /// Call this method before creating any window. If visual styles have not been enabled through + /// , the effective mode remains . + /// Passing has the same effect as not calling + /// . + /// + /// + public static void SetDefaultVisualStylesMode(VisualStylesMode styleSetting) + { + if (s_defaultVisualStylesMode is { } current && current != styleSetting) + { + throw new InvalidOperationException(SR.Application_VisualStylesModeCanOnlyBeSetOnce); + } + + // Without visual styles enabled, the only effective mode is Disabled. + s_defaultVisualStylesMode = UseVisualStyles ? styleSetting : VisualStylesMode.Disabled; + } + /// /// Gets or sets the format string to apply to top level window captions /// when they are displayed with a warning banner. @@ -980,6 +1030,13 @@ public static void EnableVisualStyles() Debug.Assert(UseVisualStyles, "Enable Visual Styles failed"); s_comCtlSupportsVisualStylesInitialized = false; + + // Keep the default visual styles mode in sync when EnableVisualStyles is called after + // SetDefaultVisualStylesMode(VisualStylesMode.Disabled): an explicitly disabled mode becomes Classic. + if (UseVisualStyles && s_defaultVisualStylesMode == VisualStylesMode.Disabled) + { + s_defaultVisualStylesMode = VisualStylesMode.Classic; + } } /// diff --git a/src/System.Windows.Forms/System/Windows/Forms/Control.cs b/src/System.Windows.Forms/System/Windows/Forms/Control.cs index 14efc5014ff..a45099b428c 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Control.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Control.cs @@ -146,6 +146,7 @@ public unsafe partial class Control : private protected static readonly object s_paddingChangedEvent = new(); private static readonly object s_previewKeyDownEvent = new(); private static readonly object s_dataContextEvent = new(); + private static readonly object s_visualStylesModeChangedEvent = new(); private static MessageId s_threadCallbackMessage; private static ContextCallback? s_invokeMarshaledCallbackHelperDelegate; @@ -224,6 +225,7 @@ public unsafe partial class Control : private static readonly int s_cacheTextFieldProperty = PropertyStore.CreateKey(); private static readonly int s_ambientPropertiesServiceProperty = PropertyStore.CreateKey(); private static readonly int s_dataContextProperty = PropertyStore.CreateKey(); + private static readonly int s_visualStylesModeProperty = PropertyStore.CreateKey(); private static readonly int s_deviceDpiInternal = PropertyStore.CreateKey(); private static readonly int s_originalDeviceDpiInternal = PropertyStore.CreateKey(); @@ -856,6 +858,80 @@ private bool ShouldSerializeDataContext() private void ResetDataContext() => Properties.RemoveValue(s_dataContextProperty); + /// + /// Gets or sets how the control renders itself when visual styles are applied. This is an ambient property. + /// + /// + /// The for the control. When not explicitly set, the value is inherited + /// from the parent control, or, for a top-level control, from . + /// + /// + /// + /// As an ambient property, a control that does not have its set explicitly + /// inherits the value from its parent, or, if it has no parent, from + /// . Derived controls can override + /// to pin themselves to a specific renderer version for backward + /// compatibility (see for an example). + /// + /// + [SRCategory(nameof(SR.CatAppearance))] + [EditorBrowsable(EditorBrowsableState.Always)] + [SRDescription(nameof(SR.ControlVisualStylesModeDescr))] + public VisualStylesMode VisualStylesMode + { + get => Properties.TryGetValue(s_visualStylesModeProperty, out VisualStylesMode value) + ? value + : ParentInternal?.VisualStylesMode ?? DefaultVisualStylesMode; + set + { + // Can't use the source generated enum validator here, since it cannot deal with [Experimental]. + _ = value switch + { + VisualStylesMode.Classic => value, + VisualStylesMode.Disabled => value, + VisualStylesMode.Net11 => value, + VisualStylesMode.Latest => value, + _ => throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(VisualStylesMode)) + }; + + if (value == VisualStylesMode) + { + return; + } + + // When VisualStylesMode differed from its parent before but is about to become the same, + // we remove it altogether so it can again inherit the value from its parent. + if (Properties.ContainsKey(s_visualStylesModeProperty) && ParentInternal?.VisualStylesMode == value) + { + Properties.RemoveValue(s_visualStylesModeProperty); + OnVisualStylesModeChanged(EventArgs.Empty); + return; + } + + Properties.AddValue(s_visualStylesModeProperty, value); + OnVisualStylesModeChanged(EventArgs.Empty); + } + } + + private bool ShouldSerializeVisualStylesMode() + => Properties.ContainsKey(s_visualStylesModeProperty); + + private void ResetVisualStylesMode() + => Properties.RemoveValue(s_visualStylesModeProperty); + + /// + /// Gets the default for the control, which is ambient to + /// . + /// + /// The default visual styles mode for the control. + /// + /// + /// Derived controls can override this property to pin themselves to a specific renderer version when their + /// rendering or layout depends on it, independent of the application-wide default. + /// + /// + protected virtual VisualStylesMode DefaultVisualStylesMode => Application.DefaultVisualStylesMode; + /// /// The background color of this control. This is an ambient property and /// will always return a non-null value. @@ -3739,6 +3815,19 @@ public event EventHandler? DataContextChanged remove => Events.RemoveHandler(s_dataContextEvent, value); } + /// + /// Occurs when the value of the property changes. + /// + [SRCategory(nameof(SR.CatAppearance))] + [Browsable(true)] + [EditorBrowsable(EditorBrowsableState.Advanced)] + [SRDescription(nameof(SR.ControlVisualStylesModeChangedDescr))] + public event EventHandler? VisualStylesModeChanged + { + add => Events.AddHandler(s_visualStylesModeChangedEvent, value); + remove => Events.RemoveHandler(s_visualStylesModeChangedEvent, value); + } + [SRCategory(nameof(SR.CatDragDrop))] [SRDescription(nameof(SR.ControlOnDragDropDescr))] public event DragEventHandler? DragDrop @@ -6829,6 +6918,34 @@ protected virtual void OnDataContextChanged(EventArgs e) } } + /// + /// Raises the event. Inheriting classes should override this method + /// to handle the event, and call . + /// to forward the event to any registered listeners. + /// + /// An that contains the event data. + [EditorBrowsable(EditorBrowsableState.Advanced)] + protected virtual void OnVisualStylesModeChanged(EventArgs e) + { + if (GetAnyDisposingInHierarchy()) + { + return; + } + + if (Events[s_visualStylesModeChangedEvent] is EventHandler eventHandler) + { + eventHandler(this, e); + } + + if (ChildControls is { } children) + { + for (int i = 0; i < children.Count; i++) + { + children[i].OnParentVisualStylesModeChanged(e); + } + } + } + [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnDockChanged(EventArgs e) { @@ -7042,6 +7159,29 @@ protected virtual void OnParentDataContextChanged(EventArgs e) OnDataContextChanged(e); } + /// + /// Occurs when the property of the parent of this control changes. + /// + /// An that contains the event data. + [EditorBrowsable(EditorBrowsableState.Advanced)] + protected virtual void OnParentVisualStylesModeChanged(EventArgs e) + { + if (Properties.ContainsKey(s_visualStylesModeProperty) + && Properties.GetValueOrDefault(s_visualStylesModeProperty) == Parent?.VisualStylesMode) + { + // Same as the parent value, make it ambient again by removing it. + Properties.RemoveValue(s_visualStylesModeProperty); + + // Even though internally we don't store it any longer, and the value we had stored + // therefore changed, technically the value remains the same, so we don't raise the + // VisualStylesModeChanged event. + return; + } + + // In every other case we're going to raise the event. + OnVisualStylesModeChanged(e); + } + [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnParentEnabledChanged(EventArgs e) { diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/Appearance.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/Appearance.cs index fb144cac774..83aacaaf244 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/Appearance.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/Appearance.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Windows.Forms; @@ -17,4 +17,15 @@ public enum Appearance /// The appearance of a Windows button. /// Button = 1, + + /// + /// The appearance of a modern UI toggle switch. + /// + /// + /// + /// This value has no effect when is set to + /// or . + /// + /// + ToggleSwitch = 2 } diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/Button.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/Button.cs index e76dd755f29..5843696f0cb 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/Button.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/Button.cs @@ -148,40 +148,6 @@ public virtual DialogResult DialogResult } } - /// - /// Defines, whether the control is owner-drawn. Based on this, - /// the UserPaint flags get set, which in turn makes it later - /// a Win32 controls, which we wrap (OwnerDraw == false) or not, and then - /// we draw ourselves. If the user wants to opt out of DarkMode, we can no - /// longer force (wrapping) System-Painting for FlatStyle.Standard, and we - /// need this then also here and now, before CreateParams is called. - /// - private protected override bool OwnerDraw - { - get - { - if (Application.IsDarkModeEnabled - - // The SystemRenderer cannot render images. So, we flip to our - // own DarkMode renderer, if we need to render images, except if... - && Image is null - // ...or a BackgroundImage, except if... - && BackgroundImage is null - // ...the user wants to opt out of implicit DarkMode rendering. - && DarkModeRequestState is true - - // And all of this only counts for FlatStyle.Standard. For the - // rest, we're using specific renderers anyway, which check - // themselves on demand, if they need to apply Light- or DarkMode. - && FlatStyle == FlatStyle.Standard) - { - return false; - } - - return base.OwnerDraw; - } - } - internal override bool SupportsUiaProviders => true; /// diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonBase.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonBase.cs index 26c3292e175..f7fe95af5ff 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonBase.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonBase.cs @@ -1256,6 +1256,22 @@ protected override void OnPaint(PaintEventArgs pevent) base.OnPaint(pevent); } + /// + protected override void OnVisualStylesModeChanged(EventArgs e) + { + base.OnVisualStylesModeChanged(e); + + // The button adapter is selected based on VisualStylesMode, so drop the cached adapter and + // force it to be recreated (and the button repainted) on the next paint. + _adapter = null; + _cachedAdapterType = (FlatStyle)(-1); + + if (IsHandleCreated) + { + Invalidate(); + } + } + protected override void OnParentChanged(EventArgs e) { base.OnParentChanged(e); diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ButtonDarkModeAdapter.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ButtonDarkModeAdapter.cs index a85dd3ed4cc..8db1ce8d28b 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ButtonDarkModeAdapter.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ButtonDarkModeAdapter.cs @@ -12,14 +12,22 @@ internal class ButtonDarkModeAdapter : ButtonBaseAdapter internal ButtonDarkModeAdapter(ButtonBase control) : base(control) { + bool modern = control.VisualStylesMode >= VisualStylesMode.Net11; + _buttonDarkModeRenderer = control.FlatStyle switch { - FlatStyle.Standard => new FlatButtonDarkModeRenderer(), - FlatStyle.Flat => new FlatButtonDarkModeRenderer(), - FlatStyle.Popup => new PopupButtonDarkModeRenderer(), + // With VisualStyles (.NET 11+) the modern, WinUI-inspired renderer is used for the owner-drawn + // styles. Otherwise FlatStyle.Standard renders with a conservative owner-drawn renderer that mimics + // the dark-mode system button (instead of delegating to the Win32 control); this makes the owner-drawn + // path reachable and lets Standard buttons support images, focus cues, etc. + FlatStyle.Standard => modern ? new ModernButtonDarkModeRenderer() : new SystemButtonDarkModeRenderer(), + FlatStyle.Flat => modern ? new ModernButtonDarkModeRenderer() : new FlatButtonDarkModeRenderer(), + FlatStyle.Popup => modern ? new ModernButtonDarkModeRenderer() : new PopupButtonDarkModeRenderer(), FlatStyle.System => new SystemButtonDarkModeRenderer(), _ => throw new ArgumentOutOfRangeException(nameof(control)) }; + + _buttonDarkModeRenderer.DeviceDpi = control.DeviceDpi; } private ButtonDarkModeRendererBase ButtonDarkModeRenderer => diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ButtonDarkModeRendererBase.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ButtonDarkModeRendererBase.cs index 9d655a618b0..b0834ee0070 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ButtonDarkModeRendererBase.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ButtonDarkModeRendererBase.cs @@ -14,6 +14,17 @@ internal abstract partial class ButtonDarkModeRendererBase : IButtonRenderer // Define padding values for each renderer type private protected abstract Padding PaddingCore { get; } + /// + /// The device DPI of the control being rendered. Set by the adapter before each paint so renderers + /// can DPI-scale their logical (96-DPI) constants. Defaults to 96 (100%). + /// + internal int DeviceDpi { get; set; } = 96; + + /// + /// Scales a logical (96-DPI) value to the current . + /// + private protected int Scale(int logicalValue) => (int)Math.Round(logicalValue * (DeviceDpi / 96.0)); + /// /// Clears the background with the parent's background color or the control's background color if no parent is available. /// diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/DarkModeAdapterFactory.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/DarkModeAdapterFactory.cs index 55552647bce..bf7f7144dfa 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/DarkModeAdapterFactory.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/DarkModeAdapterFactory.cs @@ -5,18 +5,25 @@ namespace System.Windows.Forms.ButtonInternal; internal static class DarkModeAdapterFactory { + // The owner-drawn dark/modern adapter is used when dark mode is enabled (conservative renderer) or when + // the control opts into the modern .NET 11 visual styles (modern renderer, in either dark or light scheme). + private static bool UseOwnerDrawnAdapter(ButtonBase control) + { + return Application.IsDarkModeEnabled || control.VisualStylesMode >= VisualStylesMode.Net11; + } + public static ButtonBaseAdapter CreateFlatAdapter(ButtonBase control) => - Application.IsDarkModeEnabled + UseOwnerDrawnAdapter(control) ? new ButtonDarkModeAdapter(control) : new ButtonFlatAdapter(control); public static ButtonBaseAdapter CreateStandardAdapter(ButtonBase control) => - Application.IsDarkModeEnabled + UseOwnerDrawnAdapter(control) ? new ButtonDarkModeAdapter(control) : new ButtonStandardAdapter(control); public static ButtonBaseAdapter CreatePopupAdapter(ButtonBase control) => - Application.IsDarkModeEnabled + UseOwnerDrawnAdapter(control) ? new ButtonDarkModeAdapter(control) : new ButtonPopupAdapter(control); } diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ModernButtonDarkModeRenderer.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ModernButtonDarkModeRenderer.cs new file mode 100644 index 00000000000..ac1ea0c013e --- /dev/null +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ModernButtonDarkModeRenderer.cs @@ -0,0 +1,199 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms.VisualStyles; + +namespace System.Windows.Forms; + +/// +/// Modern, WinUI-inspired push button renderer used when is +/// or later. It supports both dark and light color schemes and draws a +/// rounded button area, an optional dark gap ring, and a rounded focus ring for the focused button. +/// +/// +/// +/// The visual is intentionally driven by a small set of DPI-scaled constants so the appearance can be +/// fine-tuned during exploratory testing. All widths are expressed in logical (96-DPI) pixels. +/// +/// +internal sealed class ModernButtonDarkModeRenderer : ButtonDarkModeRendererBase +{ + // Logical (96-DPI) layout constants. DPI-scaled via the base Scale() helper. + private const int FocusRingThicknessLogical = 2; + private const int FocusGapThicknessLogical = 1; + private const int OuterBreathingLogical = 1; + private const int CornerRadiusLogical = 6; + private const int ContentInsetLogical = 4; + + // Dark scheme - default (accept) button area. + private static readonly Color s_darkDefaultNormal = Color.FromArgb(0x4C, 0xC2, 0xFF); + private static readonly Color s_darkDefaultHover = Color.FromArgb(0x47, 0xB1, 0xE8); + private static readonly Color s_darkDefaultPressed = Color.FromArgb(0x42, 0xA1, 0xD2); + + // Dark scheme - normal button area. + private static readonly Color s_darkNormal = Color.FromArgb(0x2D, 0x2D, 0x2D); + private static readonly Color s_darkNormalHover = Color.FromArgb(0x32, 0x32, 0x32); + private static readonly Color s_darkNormalPressed = Color.FromArgb(0x2A, 0x2A, 0x2A); + private static readonly Color s_darkDisabled = Color.FromArgb(0x25, 0x25, 0x25); + + private static readonly Color s_darkDefaultText = Color.Black; + private static readonly Color s_darkNormalText = Color.FromArgb(0xF0, 0xF0, 0xF0); + private static readonly Color s_darkDisabledText = Color.FromArgb(0x88, 0x88, 0x88); + + private static readonly Color s_darkGap = Color.FromArgb(0x0A, 0x0A, 0x0A); + private static readonly Color s_darkFocusRing = Color.White; + + // Light (WinUI) scheme - normal button area. + private static readonly Color s_lightNormal = Color.FromArgb(0xFB, 0xFB, 0xFB); + private static readonly Color s_lightNormalHover = Color.FromArgb(0xF9, 0xF9, 0xF9); + private static readonly Color s_lightNormalPressed = Color.FromArgb(0xF5, 0xF5, 0xF5); + private static readonly Color s_lightDisabled = Color.FromArgb(0xFA, 0xFA, 0xFA); + private static readonly Color s_lightBorder = Color.FromArgb(0xD0, 0xD0, 0xD0); + + private static readonly Color s_lightNormalText = Color.FromArgb(0x1A, 0x1A, 0x1A); + private static readonly Color s_lightDisabledText = Color.FromArgb(0xA0, 0xA0, 0xA0); + private static readonly Color s_lightDefaultText = Color.White; + + private static bool IsDark => Application.IsDarkModeEnabled; + + private int FocusRingThickness => Math.Max(1, Scale(FocusRingThicknessLogical)); + + private int FocusGapThickness => Math.Max(1, Scale(FocusGapThicknessLogical)); + + private int CornerRadius => Math.Max(1, Scale(CornerRadiusLogical)); + + private protected override Padding PaddingCore + => new(FocusRingThickness + FocusGapThickness + Math.Max(0, Scale(OuterBreathingLogical))); + + public override Rectangle DrawButtonBackground( + Graphics graphics, + Rectangle bounds, + PushButtonState state, + bool isDefault, + Color backColor) + { + GraphicsState? saved = graphics.Save(); + try + { + graphics.SmoothingMode = SmoothingMode.AntiAlias; + + int radius = CornerRadius; + using (var brush = backColor.GetCachedSolidBrushScope()) + { + graphics.FillRoundedRectangle(brush, bounds, new Size(radius, radius)); + } + + // A subtle border for the light, non-default button, matching the WinUI neutral button. + if (!IsDark && !isDefault && state != PushButtonState.Disabled) + { + using var borderPen = s_lightBorder.GetCachedPenScope(); + Rectangle borderRect = new(bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); + graphics.DrawRoundedRectangle(borderPen, borderRect, new Size(radius, radius)); + } + } + finally + { + if (saved is not null) + { + graphics.Restore(saved); + } + } + + int inset = Scale(ContentInsetLogical); + return Rectangle.Inflate(bounds, -inset, -inset); + } + + public override void DrawFocusIndicator(Graphics graphics, Rectangle bounds, bool isDefault) + { + GraphicsState? saved = graphics.Save(); + try + { + graphics.SmoothingMode = SmoothingMode.AntiAlias; + + int radius = CornerRadius + FocusGapThickness + FocusRingThickness; + + // Dark gap ring between the focus ring and the button area. + Color gapColor = IsDark ? s_darkGap : SystemColors.Window; + int gapInset = FocusRingThickness + (FocusGapThickness / 2); + Rectangle gapRect = Rectangle.Inflate(bounds, -gapInset, -gapInset); + gapRect.Width -= 1; + gapRect.Height -= 1; + using (var gapPen = gapColor.GetCachedPenScope(FocusGapThickness)) + { + graphics.DrawRoundedRectangle(gapPen, gapRect, new Size(radius, radius)); + } + + // Outer rounded focus ring. + Color ringColor = IsDark ? s_darkFocusRing : SystemColors.WindowText; + int ringInset = FocusRingThickness / 2; + Rectangle ringRect = Rectangle.Inflate(bounds, -ringInset, -ringInset); + ringRect.Width -= 1; + ringRect.Height -= 1; + using var ringPen = ringColor.GetCachedPenScope(FocusRingThickness); + graphics.DrawRoundedRectangle(ringPen, ringRect, new Size(radius + ringInset, radius + ringInset)); + } + finally + { + if (saved is not null) + { + graphics.Restore(saved); + } + } + } + + public override Color GetTextColor(PushButtonState state, bool isDefault) + { + if (state == PushButtonState.Disabled) + { + return IsDark ? s_darkDisabledText : s_lightDisabledText; + } + + if (isDefault) + { + return IsDark ? s_darkDefaultText : s_lightDefaultText; + } + + return IsDark ? s_darkNormalText : s_lightNormalText; + } + + public override Color GetBackgroundColor(PushButtonState state, bool isDefault) + { + if (state == PushButtonState.Disabled) + { + return IsDark ? s_darkDisabled : s_lightDisabled; + } + + if (isDefault) + { + return IsDark + ? state switch + { + PushButtonState.Hot => s_darkDefaultHover, + PushButtonState.Pressed => s_darkDefaultPressed, + _ => s_darkDefaultNormal + } + : state switch + { + PushButtonState.Hot => ControlPaint.Light(SystemColors.Highlight, 0.1f), + PushButtonState.Pressed => ControlPaint.Dark(SystemColors.Highlight, 0.1f), + _ => SystemColors.Highlight + }; + } + + return IsDark + ? state switch + { + PushButtonState.Hot => s_darkNormalHover, + PushButtonState.Pressed => s_darkNormalPressed, + _ => s_darkNormal + } + : state switch + { + PushButtonState.Hot => s_lightNormalHover, + PushButtonState.Pressed => s_lightNormalPressed, + _ => s_lightNormal + }; + } +} diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/CheckBox.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/CheckBox.cs index 57526b2644b..fd532dd4d7b 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/CheckBox.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/CheckBox.cs @@ -29,6 +29,8 @@ public partial class CheckBox : ButtonBase private CheckState _checkState; private Appearance _appearance; + private Rendering.CheckBox.AnimatedToggleSwitchRenderer? _toggleSwitchRenderer; + private int _flatSystemStylePaddingWidth; private int _flatSystemStyleMinimumHeight; @@ -80,6 +82,7 @@ public Appearance Appearance // the handle if they differ. Since we hijack FlatStyle.Standard for DarkMode, the transition // between Normal and Button appearance is critical for updating the OwnerDraw flag. UpdateOwnerDraw(); + UpdateToggleSwitchStyles(); // If handle wasn't recreated (OwnerDraw state didn't change), refresh the appearance. if (OwnerDraw) @@ -97,16 +100,44 @@ public Appearance Appearance } private protected override bool OwnerDraw => + // The modern toggle switch is always owner-drawn (so UserPaint is enabled for it). + IsToggleSwitchAppearance + || // We want NO owner draw ONLY when we're // * In Dark Mode // * When _then_ the Appearance is Button // * But then ONLY when we're rendering with FlatStyle.Standard // (because that would let us usually let us draw with the VisualStyleRenderers, // which cause HighDPI issues in Dark Mode). - (!Application.IsDarkModeEnabled + ((!Application.IsDarkModeEnabled || Appearance != Appearance.Button || FlatStyle != FlatStyle.Standard) - && base.OwnerDraw; + && base.OwnerDraw); + + /// + /// Gets a value indicating whether the check box should render as the modern, animated toggle switch. + /// + private bool IsToggleSwitchAppearance + { + get + { + return Appearance == Appearance.ToggleSwitch + && VisualStylesMode >= VisualStylesMode.Net11 + && !ThreeState; + } + } + + private Rendering.CheckBox.AnimatedToggleSwitchRenderer ToggleSwitchRenderer => + _toggleSwitchRenderer ??= new(this, Rendering.CheckBox.ModernCheckBoxStyle.Rounded); + + private void UpdateToggleSwitchStyles() + { + if (IsToggleSwitchAppearance) + { + // Owner-paint with WinForms double buffering for a flicker-free, fluent animation. + SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true); + } + } [SRCategory(nameof(SR.CatPropertyChanged))] [SRDescription(nameof(SR.CheckBoxOnAppearanceChangedDescr))] @@ -199,6 +230,14 @@ public CheckState CheckState return; } + // For the animated toggle switch, stop any in-flight animation (leaving the thumb at its current + // position) before the state changes, then start a fresh animation toward the new position. + bool animateToggleSwitch = IsToggleSwitchAppearance && IsHandleCreated; + if (animateToggleSwitch) + { + ToggleSwitchRenderer.StopAnimation(); + } + bool oldChecked = Checked; _checkState = value; @@ -218,6 +257,11 @@ public CheckState CheckState _notifyAccessibilityStateChangedNeeded = !checkedChanged; OnCheckStateChanged(EventArgs.Empty); _notifyAccessibilityStateChangedNeeded = false; + + if (animateToggleSwitch) + { + ToggleSwitchRenderer.StartAnimation(); + } } } @@ -288,6 +332,17 @@ private void ScaleConstants() internal override Size GetPreferredSizeCore(Size proposedConstraints) { + if (IsToggleSwitchAppearance) + { + int dpiScale = (int)(DeviceDpi / 96f); + Size toggleTextSize = TextRenderer.MeasureText(Text, Font); + int switchWidth = 50 * dpiScale; + int switchHeight = 25 * dpiScale; + int totalWidth = toggleTextSize.Width + switchWidth + (20 * dpiScale); + int totalHeight = Math.Max(toggleTextSize.Height, switchHeight); + return new Size(totalWidth, totalHeight); + } + if (Appearance == Appearance.Button) { ButtonStandardAdapter adapter = new(this); @@ -497,6 +552,47 @@ protected override void OnHandleCreated(EventArgs e) { PInvokeCore.SendMessage(this, PInvoke.BM_SETCHECK, (WPARAM)(int)_checkState); } + + UpdateToggleSwitchStyles(); + } + + /// + protected override void OnPaint(PaintEventArgs pevent) + { + if (IsToggleSwitchAppearance) + { + using GraphicsStateScope scope = new(pevent.Graphics); + ToggleSwitchRenderer.RenderControl(pevent.Graphics); + return; + } + + base.OnPaint(pevent); + } + + /// + protected override void OnVisualStylesModeChanged(EventArgs e) + { + base.OnVisualStylesModeChanged(e); + + // Entering or leaving the modern toggle-switch appearance changes whether the control is owner-drawn. + UpdateOwnerDraw(); + UpdateToggleSwitchStyles(); + + if (IsHandleCreated) + { + Invalidate(); + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _toggleSwitchRenderer?.Dispose(); + _toggleSwitchRenderer = null; + } + + base.Dispose(disposing); } /// diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs index 0ec7ce5fdb5..bec38ade229 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs @@ -755,15 +755,20 @@ public event EventHandler? MultilineChanged remove => Events.RemoveHandler(s_multilineChangedEvent, value); } - [Browsable(false)] - [EditorBrowsable(EditorBrowsableState.Never)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Browsable(true)] + [EditorBrowsable(EditorBrowsableState.Always)] public new Padding Padding { get => base.Padding; set => base.Padding = value; } + private new bool ShouldSerializePadding() + => Padding != DefaultPadding; + + private void ResetPadding() + => Padding = DefaultPadding; + [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] diff --git a/src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimatedControlRenderer.cs b/src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimatedControlRenderer.cs new file mode 100644 index 00000000000..7a44245ebb0 --- /dev/null +++ b/src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimatedControlRenderer.cs @@ -0,0 +1,152 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Drawing; + +namespace System.Windows.Forms.Rendering.Animation; + +/// +/// Represents an abstract base class for animated control renderers. +/// +/// The control associated with the renderer. +internal abstract class AnimatedControlRenderer(Control control) : IDisposable +{ + private bool _disposedValue; + protected float AnimationProgress = 1; + + /// + /// Callback for the animation progress. This method is called by the animation manager on each + /// frame tick delivered by HighPrecisionTimer. + /// + /// A fraction between 0 and 1 representing the animation progress. + public virtual void AnimationProc(float animationProgress) + { + AnimationProgress = animationProgress; + } + + /// + /// Called when the control needs to be painted. + /// + /// The to paint the control. + public abstract void RenderControl(Graphics graphics); + + /// + /// Invalidates the control, causing it to be redrawn, which in turns triggers + /// . + /// + public void Invalidate() => control.Invalidate(); + + /// + /// Starts the animation and gets the animation parameters. + /// + public void StartAnimation() + { + if (IsRunning) + { + return; + } + + // Get the animation parameters. + (int animationDuration, AnimationCycle animationCycle) = OnAnimationStarted(); + + // Register the renderer with the animation manager. + AnimationManager.RegisterOrUpdateAnimationRenderer( + this, + animationDuration, + animationCycle); + + IsRunning = true; + } + + internal void StopAnimationInternal() => IsRunning = false; + + public void RestartAnimation() + { + if (IsRunning) + { + StopAnimation(); + } + + StartAnimation(); + } + + /// + /// Called in a derived class when the animation starts. The derived class returns the animation duration and cycle type. + /// + /// + /// Tuple containing the animation duration and cycle type. + /// + protected abstract (int animationDuration, AnimationCycle animationCycle) OnAnimationStarted(); + + /// + /// Called by the animation manager when the animation ends. + /// + internal void EndAnimation() + { + OnAnimationEnded(); + } + + /// + /// Called in a derived class when the animation ends. + /// The derived class can perform any cleanup or state change operations. + /// + protected abstract void OnAnimationEnded(); + + /// + /// Can be called by an implementing control, when the animation needs to be stopped or restarted. + /// + public void StopAnimation() + { + AnimationManager.Suspend(this); + OnAnimationStopped(); + } + + /// + /// Called in the derived class when the animation is stopped. + /// The derived class can perform any cleanup or state change operations. + /// + protected abstract void OnAnimationStopped(); + + /// + /// Gets the DPI scale of the control. + /// + protected int DpiScale => (int)(control.DeviceDpi / 96f); + + /// + /// Gets a value indicating whether the animation is running. + /// + public bool IsRunning { get; private set; } + + /// + /// Gets the control associated with the renderer. + /// + protected Control Control => control; + + /// + /// Releases the unmanaged resources used by the and optionally releases the managed resources. + /// + /// to release both managed and unmanaged resources; to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if (!_disposedValue) + { + if (disposing) + { + // Remove the renderer from the animation manager. + AnimationManager.UnregisterAnimationRenderer(this); + } + + _disposedValue = true; + } + } + + /// + /// Releases all resources used by the . + /// + public void Dispose() + { + // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method. + Dispose(disposing: true); + GC.SuppressFinalize(this); + } +} diff --git a/src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationCycle.cs b/src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationCycle.cs new file mode 100644 index 00000000000..0dfac5f12f6 --- /dev/null +++ b/src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationCycle.cs @@ -0,0 +1,11 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace System.Windows.Forms.Rendering.Animation; + +internal enum AnimationCycle +{ + Once, + Loop, + Bounce +} diff --git a/src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationManager.AnimationRendererItem.cs b/src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationManager.AnimationRendererItem.cs new file mode 100644 index 00000000000..dae4505a21b --- /dev/null +++ b/src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationManager.AnimationRendererItem.cs @@ -0,0 +1,25 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace System.Windows.Forms.Rendering.Animation; + +internal partial class AnimationManager +{ + private class AnimationRendererItem + { + public long StopwatchTarget; + + public AnimationRendererItem(AnimatedControlRenderer renderer, int animationDuration, AnimationCycle animationCycle) + { + Renderer = renderer; + AnimationDuration = animationDuration; + AnimationCycle = animationCycle; + } + + public AnimatedControlRenderer Renderer { get; } + public int AnimationDuration { get; set; } + public int FrameCount { get; set; } + public AnimationCycle AnimationCycle { get; set; } + public int FrameOffset { get; set; } = 1; + } +} diff --git a/src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationManager.cs b/src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationManager.cs new file mode 100644 index 00000000000..9cfc01ce919 --- /dev/null +++ b/src/System.Windows.Forms/System/Windows/Forms/Rendering/Animation/AnimationManager.cs @@ -0,0 +1,154 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Collections.Concurrent; +using System.Windows.Forms.Animation; + +namespace System.Windows.Forms.Rendering.Animation; + +/// +/// Process-wide dispatcher that drives all instances from a single +/// HighPrecisionTimer registration. +/// +/// +/// +/// The frame cadence is provided by HighPrecisionTimer (60 Hz where supported, otherwise 30 Hz). +/// Because that timer marshals its callback back to the captured when this +/// manager was constructed, the per-frame work runs on the UI thread and can invalidate controls directly. +/// +/// +internal partial class AnimationManager +{ + private readonly Stopwatch _stopwatch; + private readonly HighPrecisionTimer.TimerRegistration _timerRegistration; + + private readonly ConcurrentDictionary _renderer = []; + + private static AnimationManager? s_instance; + + private static AnimationManager Instance + => s_instance ??= new AnimationManager(); + + private AnimationManager() + { + _stopwatch = Stopwatch.StartNew(); + + // HighPrecisionTimer captures the current SynchronizationContext and posts each tick back to it, + // so OnFrameTickAsync runs on the UI thread. A SynchronizationContext is expected here because the + // first animation is always started from the UI thread. + _timerRegistration = HighPrecisionTimer.Register(OnFrameTickAsync); + + Application.ApplicationExit += (sender, e) => DisposeRenderer(); + } + + /// + /// Disposes the animation renderers and releases the timer registration. + /// + private void DisposeRenderer() + { + // Stop the timer. + _timerRegistration.Dispose(); + + foreach (AnimatedControlRenderer renderer in _renderer.Keys) + { + renderer.Dispose(); + } + } + + /// + /// Registers an animation renderer. + /// + /// The animation renderer to register. + /// The duration of the animation. + /// The animation cycle. + public static void RegisterOrUpdateAnimationRenderer( + AnimatedControlRenderer animationRenderer, + int animationDuration, + AnimationCycle animationCycle) + { + // If the renderer is already registered, update the animation parameters. + if (Instance._renderer.TryGetValue(animationRenderer, out AnimationRendererItem? renderItem)) + { + renderItem.StopwatchTarget = Instance._stopwatch.ElapsedMilliseconds + animationDuration; + renderItem.AnimationDuration = animationDuration; + renderItem.AnimationCycle = animationCycle; + + return; + } + + renderItem = new AnimationRendererItem(animationRenderer, animationDuration, animationCycle) + { + StopwatchTarget = Instance._stopwatch.ElapsedMilliseconds + animationDuration, + }; + + _ = Instance._renderer.TryAdd(animationRenderer, renderItem); + } + + /// + /// Unregisters an animation renderer. + /// + /// The animation renderer to unregister. + internal static void UnregisterAnimationRenderer(AnimatedControlRenderer animationRenderer) + { + _ = Instance._renderer.TryRemove(animationRenderer, out _); + } + + internal static void Suspend(AnimatedControlRenderer animatedControlRenderer) + { + if (Instance._renderer.TryGetValue(animatedControlRenderer, out AnimationRendererItem? renderItem)) + { + renderItem.Renderer.StopAnimationInternal(); + } + } + + /// + /// Handles a single frame tick delivered by HighPrecisionTimer (on the UI thread). + /// + private ValueTask OnFrameTickAsync(HighPrecisionTimerTick tick, CancellationToken cancellationToken) + { + long elapsedStopwatchMilliseconds = _stopwatch.ElapsedMilliseconds; + + foreach (AnimationRendererItem item in _renderer.Values) + { + if (!item.Renderer.IsRunning) + { + continue; + } + + long remainingAnimationMilliseconds = item.StopwatchTarget - elapsedStopwatchMilliseconds; + + item.FrameCount += item.FrameOffset; + + if (elapsedStopwatchMilliseconds >= item.StopwatchTarget) + { + switch (item.AnimationCycle) + { + case AnimationCycle.Once: + item.Renderer.EndAnimation(); + break; + + case AnimationCycle.Loop: + item.FrameCount = 0; + item.StopwatchTarget = elapsedStopwatchMilliseconds + item.AnimationDuration; + item.Renderer.RestartAnimation(); + break; + + case AnimationCycle.Bounce: + item.FrameOffset = -item.FrameOffset; + item.StopwatchTarget = elapsedStopwatchMilliseconds + item.AnimationDuration; + item.Renderer.RestartAnimation(); + break; + } + + continue; + } + + float progress = 1 - (remainingAnimationMilliseconds / (float)item.AnimationDuration); + + // We are already on the UI thread (HighPrecisionTimer marshalled us here), so invoke directly. + item.Renderer.AnimationProc(progress); + } + + return ValueTask.CompletedTask; + } +} diff --git a/src/System.Windows.Forms/System/Windows/Forms/Rendering/CheckBox/AnimatedToggleSwitchRenderer.cs b/src/System.Windows.Forms/System/Windows/Forms/Rendering/CheckBox/AnimatedToggleSwitchRenderer.cs new file mode 100644 index 00000000000..7e0c92054e0 --- /dev/null +++ b/src/System.Windows.Forms/System/Windows/Forms/Rendering/CheckBox/AnimatedToggleSwitchRenderer.cs @@ -0,0 +1,140 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms.Rendering.Animation; + +namespace System.Windows.Forms.Rendering.CheckBox; + +/// +/// Renders and animates a in mode. +/// Used when is or later. +/// +internal sealed class AnimatedToggleSwitchRenderer : AnimatedControlRenderer +{ + private const int AnimationDuration = 300; // milliseconds + private const int SwitchWidthLogical = 50; + private const int SwitchHeightLogical = 25; + private const int CircleDiameterLogical = 20; + private const int TextGapLogical = 10; + + private readonly ModernCheckBoxStyle _switchStyle; + + public AnimatedToggleSwitchRenderer(Control control, ModernCheckBoxStyle switchStyle) + : base(control) + { + _switchStyle = switchStyle; + } + + private Forms.CheckBox CheckBox => (Forms.CheckBox)Control; + + public override void AnimationProc(float animationProgress) + { + base.AnimationProc(animationProgress); + Invalidate(); + } + + protected override (int animationDuration, AnimationCycle animationCycle) OnAnimationStarted() + { + AnimationProgress = 1; + + return (AnimationDuration, AnimationCycle.Once); + } + + /// + /// Called from the control's OnPaint. Works both while the animation is running (driven by + /// ) and when it is settled (progress is 1). + /// + /// The graphics object to render into. + public override void RenderControl(Graphics graphics) + { + int dpiScale = DpiScale; + + int switchWidth = SwitchWidthLogical * dpiScale; + int switchHeight = SwitchHeightLogical * dpiScale; + int circleDiameter = CircleDiameterLogical * dpiScale; + int textGap = TextGapLogical * dpiScale; + + Size textSize = TextRenderer.MeasureText(Control.Text, Control.Font); + + int totalHeight = Math.Max(textSize.Height, switchHeight); + int switchY = (totalHeight - switchHeight) / 2; + int textY = (totalHeight - textSize.Height) / 2; + + graphics.Clear(Control.BackColor); + + switch (CheckBox.TextAlign) + { + case ContentAlignment.MiddleLeft: + case ContentAlignment.TopLeft: + case ContentAlignment.BottomLeft: + RenderSwitch(graphics, new Rectangle(textSize.Width + textGap, switchY, switchWidth, switchHeight), circleDiameter); + RenderText(graphics, new Point(0, textY)); + break; + + default: + RenderSwitch(graphics, new Rectangle(0, switchY, switchWidth, switchHeight), circleDiameter); + RenderText(graphics, new Point(switchWidth + textGap, textY)); + break; + } + } + + private void RenderText(Graphics graphics, Point position) => + TextRenderer.DrawText(graphics, CheckBox.Text, CheckBox.Font, position, CheckBox.ForeColor); + + private void RenderSwitch(Graphics graphics, Rectangle rect, int circleDiameter) + { + // The background color flips at 80% of the animation so the thumb travels visibly before the color change. + Color backgroundColor = CheckBox.Checked ^ (AnimationProgress < 0.8f) + ? SystemColors.Highlight + : SystemColors.ControlDark; + + Color circleColor = SystemColors.ControlText; + + // Works both for the running and settled states (settled progress is 1, so the thumb rests in place). + float circlePosition = CheckBox.Checked + ? (rect.Width - circleDiameter) * (1 - EaseOut(AnimationProgress)) + : (rect.Width - circleDiameter) * EaseOut(AnimationProgress); + + using var backgroundBrush = backgroundColor.GetCachedSolidBrushScope(); + using var circleBrush = circleColor.GetCachedSolidBrushScope(); + using var backgroundPen = SystemColors.WindowFrame.GetCachedPenScope(2 * DpiScale); + + graphics.SmoothingMode = SmoothingMode.AntiAlias; + + if (_switchStyle == ModernCheckBoxStyle.Rounded) + { + float radius = rect.Height / 2f; + + using GraphicsPath path = new(); + path.AddArc(rect.X, rect.Y, radius * 2, radius * 2, 180, 90); + path.AddArc(rect.Right - radius * 2, rect.Y, radius * 2, radius * 2, 270, 90); + path.AddArc(rect.Right - radius * 2, rect.Bottom - radius * 2, radius * 2, radius * 2, 0, 90); + path.AddArc(rect.X, rect.Bottom - radius * 2, radius * 2, radius * 2, 90, 90); + path.CloseFigure(); + + graphics.FillPath(backgroundBrush, path); + graphics.DrawPath(backgroundPen, path); + } + else + { + graphics.FillRectangle(backgroundBrush, rect); + graphics.DrawRectangle(backgroundPen, rect); + } + + graphics.FillEllipse(circleBrush, rect.X + circlePosition, rect.Y + (2.5f * DpiScale), circleDiameter, circleDiameter); + + static float EaseOut(float t) => (1 - t) * (1 - t); + } + + protected override void OnAnimationStopped() + { + AnimationProgress = 0; + } + + protected override void OnAnimationEnded() + { + AnimationProgress = 1; + } +} diff --git a/src/System.Windows.Forms/System/Windows/Forms/Rendering/CheckBox/ModernCheckBoxStyle.cs b/src/System.Windows.Forms/System/Windows/Forms/Rendering/CheckBox/ModernCheckBoxStyle.cs new file mode 100644 index 00000000000..32f35518ed3 --- /dev/null +++ b/src/System.Windows.Forms/System/Windows/Forms/Rendering/CheckBox/ModernCheckBoxStyle.cs @@ -0,0 +1,10 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace System.Windows.Forms.Rendering.CheckBox; + +internal enum ModernCheckBoxStyle +{ + Rectangular, + Rounded +} diff --git a/src/System.Windows.Forms/System/Windows/Forms/VisualStylesMode.cs b/src/System.Windows.Forms/System/Windows/Forms/VisualStylesMode.cs new file mode 100644 index 00000000000..2658846d23e --- /dev/null +++ b/src/System.Windows.Forms/System/Windows/Forms/VisualStylesMode.cs @@ -0,0 +1,41 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace System.Windows.Forms; + +/// +/// Represents the version of the visual renderer that a control or the application uses. +/// +/// +/// +/// The visual styles version controls how a control renders its adorners, borders, and layout. +/// Newer versions can adjust minimum sizes, padding, and margins to satisfy current accessibility +/// requirements without changing the behavior of applications that target an earlier version. +/// +/// +public enum VisualStylesMode : short +{ + /// + /// The classic version of the visual renderer (.NET 8 and earlier), based on version 6 of the + /// common controls library. + /// + Classic = 0, + + /// + /// Visual renderers are not in use - see . + /// Controls are based on version 5 of the common controls library. + /// + Disabled = 1, + + /// + /// The .NET 11 version of the visual renderer. Controls are rendered using the latest version + /// of the common controls library, and the adorner rendering or the layout of specific controls + /// has been improved based on the latest accessibility requirements. + /// + Net11 = 2, + + /// + /// The latest version of the visual renderer available in the running framework. + /// + Latest = short.MaxValue +} diff --git a/src/test/integration/WinformsControlsTest/Buttons.cs b/src/test/integration/WinformsControlsTest/Buttons.cs index b6b9836c74f..a369b841659 100644 --- a/src/test/integration/WinformsControlsTest/Buttons.cs +++ b/src/test/integration/WinformsControlsTest/Buttons.cs @@ -119,6 +119,14 @@ protected override void OnLoad(EventArgs e) column: 1, row: 1); + Button visualStylesButton = new() + { + AutoSize = true, + Text = "VisualStyles Buttons\u2026" + }; + visualStylesButton.Click += (s, _) => new VisualStylesButtons().Show(this); + table.Controls.Add(visualStylesButton, column: 2, row: 1); + base.OnLoad(e); } } diff --git a/src/test/integration/WinformsControlsTest/VisualStylesButtons.cs b/src/test/integration/WinformsControlsTest/VisualStylesButtons.cs new file mode 100644 index 00000000000..41fc06292f6 --- /dev/null +++ b/src/test/integration/WinformsControlsTest/VisualStylesButtons.cs @@ -0,0 +1,193 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#nullable enable + +using System.Drawing; + +namespace WinFormsControlsTest; + +/// +/// Exploratory-testing harness for the conservative and modern (.NET 11 VisualStyles) button renderers. +/// Toggle the "Modern visual styles" check box to flip every sample button between +/// and at runtime. +/// +/// +/// +/// The application-wide color mode (Classic/Dark) is a start-up, set-once setting, so to evaluate the dark +/// palette the host application must be started in dark mode. The modern vs. conservative look, however, is +/// driven by the per-control ambient property and can be toggled live here. +/// +/// +[DesignerCategory("Default")] +public sealed class VisualStylesButtons : Form +{ + private static readonly FlatStyle[] s_styles = + [ + FlatStyle.Standard, + FlatStyle.Flat, + FlatStyle.Popup, + FlatStyle.System + ]; + + private readonly List public void RenderButton( Graphics graphics, + Control control, Rectangle bounds, FlatStyle flatStyle, PushButtonState state, @@ -120,9 +122,6 @@ public void RenderButton( // Scope the graphics state so all changes are reverted after rendering using (new GraphicsStateScope(graphics)) { - // Clear the background over the whole button area. - ClearBackground(graphics, parentBackgroundColor); - // Use padding from the renderer. When the focus ring is not drawn, renderers may return a smaller // padding so the button body expands into the space the ring and its gap would otherwise occupy. Padding padding = GetContentPadding(focused && showFocusCues); @@ -133,22 +132,41 @@ public void RenderButton( width: bounds.Width - padding.Horizontal, height: bounds.Height - padding.Vertical); - // Draw button background and get content bounds - Rectangle contentBounds = DrawButtonBackground(graphics, paddedBounds, state, isDefault, focused, backColor); - - // Paint image and field using the provided delegates - paintImage(contentBounds); - - paintField(); - - if (focused && showFocusCues) + GraphicsPath? backgroundPath = CreateBackgroundPath(paddedBounds, isDefault, focused); + try { - // Draw focus indicator for other styles - DrawFocusIndicator(graphics, bounds, isDefault); + if (backgroundPath is not null) + { + ParentBackgroundRenderer.Paint(control, graphics, bounds, backgroundPath, parentBackgroundColor); + } + else + { + // Rectangular renderers still need a complete background before painting their body. + ClearBackground(graphics, parentBackgroundColor); + } + + // Draw button background and get content bounds + Rectangle contentBounds = DrawButtonBackground(graphics, paddedBounds, state, isDefault, focused, backColor); + + // Paint image and field using the provided delegates + paintImage(contentBounds); + paintField(); + + if (focused && showFocusCues) + { + // Draw focus indicator for other styles + DrawFocusIndicator(graphics, bounds, isDefault); + } + } + finally + { + backgroundPath?.Dispose(); } } } + private protected virtual GraphicsPath? CreateBackgroundPath(Rectangle bounds, bool isDefault, bool focused) => null; + public abstract Rectangle DrawButtonBackground( Graphics graphics, Rectangle bounds, diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/IButtonRenderer.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/IButtonRenderer.cs index e5b71b025ab..6bd41d27544 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/IButtonRenderer.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/IButtonRenderer.cs @@ -30,6 +30,7 @@ static void DrawButtonBorder(Graphics graphics, GraphicsPath path, Color borderC /// Renders the button with the specified style, state, and content. /// /// The graphics context to draw on. + /// The button control whose parent surface is used for exposed regions. /// The bounds of the button. /// The flat style of the button. /// The visual state of the button (normal, hot, pressed, disabled, default). @@ -41,6 +42,7 @@ static void DrawButtonBorder(Graphics graphics, GraphicsPath path, Color borderC /// An action to paint the text or field within the specified rectangle, color, and enabled state. void RenderButton( Graphics graphics, + Control control, Rectangle bounds, FlatStyle flatStyle, PushButtonState state, diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ModernButtonDarkModeRenderer.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ModernButtonDarkModeRenderer.cs index c112c0e1a12..683e808b054 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ModernButtonDarkModeRenderer.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/ModernButtonDarkModeRenderer.cs @@ -25,6 +25,7 @@ internal sealed class ModernButtonDarkModeRenderer : ButtonDarkModeRendererBase private const int FocusGapThicknessLogical = 1; private const int FocusedCornerRadiusLogical = 6; private const int UnfocusedCornerRadiusLogical = 8; + private const int BorderThicknessLogical = 1; private const int ContentInsetLogical = 4; // Dark scheme - default (accept) button area. @@ -88,6 +89,16 @@ private protected override Padding GetContentPadding(bool focusRingVisible) private protected override bool UseModernStateDefaults => true; + private protected override GraphicsPath? CreateBackgroundPath(Rectangle bounds, bool isDefault, bool focused) + { + if (bounds.Width <= 0 || bounds.Height <= 0) + { + return null; + } + + return CreateRoundedPath(GetPathBounds(bounds), GetCornerRadius(focused, isDefault)); + } + public override Rectangle DrawButtonBackground( Graphics graphics, Rectangle bounds, @@ -101,19 +112,31 @@ public override Rectangle DrawButtonBackground( { graphics.SmoothingMode = SmoothingMode.AntiAlias; - int radius = GetCornerRadius(focused, isDefault); - using (var brush = backColor.GetCachedSolidBrushScope()) - { - graphics.FillRoundedRectangle(brush, bounds, new Size(radius, radius)); - } + RectangleF pathBounds = GetPathBounds(bounds); + float radius = GetCornerRadius(focused, isDefault); + int borderThickness = ScaleBorderThickness( + Math.Max(1, Scale(BorderThicknessLogical))); - // A subtle border for the light, non-default button, matching the WinUI neutral button. - if (!IsDark && !isDefault && state != PushButtonState.Disabled) + if (!IsDark + && !isDefault + && state != PushButtonState.Disabled + && borderThickness > 0) { - using var borderPen = s_lightBorder.GetCachedPenScope(); - Rectangle borderRect = new(bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1); - graphics.DrawRoundedRectangle(borderPen, borderRect, new Size(radius, radius)); + Color borderColor = ResolveBorderColor(s_lightBorder); + using var borderBrush = borderColor.GetCachedSolidBrushScope(); + using GraphicsPath borderPath = CreateRingPath( + pathBounds, + radius, + borderThickness); + graphics.FillPath(borderBrush, borderPath); + + pathBounds = Inset(pathBounds, borderThickness); + radius = Math.Max(1, radius - (2 * borderThickness)); } + + using var brush = backColor.GetCachedSolidBrushScope(); + using GraphicsPath bodyPath = CreateRoundedPath(pathBounds, radius); + graphics.FillPath(brush, bodyPath); } finally { @@ -139,30 +162,28 @@ public override void DrawFocusIndicator(Graphics graphics, Rectangle bounds, boo return; } - int radius = GetCornerRadius(focused: true, isDefault: isDefault) - + FocusGapThickness - + FocusRingThickness; + RectangleF outerBounds = GetPathBounds(bounds); + int bodyInset = FocusRingThickness + FocusGapThickness; + float outerRadius = GetCornerRadius(focused: true, isDefault: isDefault) + + (2 * bodyInset); - // Dark gap ring between the focus ring and the button area. Color gapColor = IsDark ? s_darkGap : SystemColors.Window; - int gapInset = FocusRingThickness + (FocusGapThickness / 2); - Rectangle gapRect = Rectangle.Inflate(bounds, -gapInset, -gapInset); - gapRect.Width -= 1; - gapRect.Height -= 1; - using (var gapPen = gapColor.GetCachedPenScope(FocusGapThickness)) + using (var gapBrush = gapColor.GetCachedSolidBrushScope()) { - graphics.DrawRoundedRectangle(gapPen, gapRect, new Size(radius, radius)); + using GraphicsPath gapPath = CreateRingPath( + Inset(outerBounds, FocusRingThickness), + outerRadius - (2 * FocusRingThickness), + FocusGapThickness); + graphics.FillPath(gapBrush, gapPath); } - // Outer rounded focus ring. Color ringColor = ResolveBorderColor(IsDark ? s_darkFocusRing : SystemColors.WindowText); - int ringInset = FocusRingThickness / 2; - Rectangle ringRect = Rectangle.Inflate(bounds, -ringInset, -ringInset); - ringRect.Width -= 1; - ringRect.Height -= 1; - - using var ringPen = ringColor.GetCachedPenScope(FocusRingThickness); - graphics.DrawRoundedRectangle(ringPen, ringRect, new Size(radius + ringInset, radius + ringInset)); + using var ringBrush = ringColor.GetCachedSolidBrushScope(); + using GraphicsPath ringPath = CreateRingPath( + outerBounds, + outerRadius, + FocusRingThickness); + graphics.FillPath(ringBrush, ringPath); } finally { @@ -226,4 +247,40 @@ public override Color GetBackgroundColor(PushButtonState state, bool isDefault) _ => s_lightNormal }; } + + private static RectangleF GetPathBounds(Rectangle bounds) + => new( + bounds.X, + bounds.Y, + Math.Max(1, bounds.Width - 1), + Math.Max(1, bounds.Height - 1)); + + private static RectangleF Inset(RectangleF bounds, float inset) + => new( + bounds.X + inset, + bounds.Y + inset, + Math.Max(1, bounds.Width - (2 * inset)), + Math.Max(1, bounds.Height - (2 * inset))); + + private static GraphicsPath CreateRoundedPath(RectangleF bounds, float radius) + { + GraphicsPath path = new(); + float clampedRadius = Math.Clamp(radius, 1, Math.Min(bounds.Width, bounds.Height)); + path.AddRoundedRectangle(bounds, new SizeF(clampedRadius, clampedRadius)); + return path; + } + + private static GraphicsPath CreateRingPath( + RectangleF outerBounds, + float outerRadius, + float thickness) + { + GraphicsPath path = CreateRoundedPath(outerBounds, outerRadius); + RectangleF innerBounds = Inset(outerBounds, thickness); + float innerRadius = Math.Max(1, outerRadius - (2 * thickness)); + using GraphicsPath innerPath = CreateRoundedPath(innerBounds, innerRadius); + path.FillMode = FillMode.Alternate; + path.AddPath(innerPath, connect: false); + return path; + } } diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/SystemButtonDarkModeRenderer.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/SystemButtonDarkModeRenderer.cs index 7a18789fa10..b478671e27d 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/SystemButtonDarkModeRenderer.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/ButtonInternal/DarkMode/SystemButtonDarkModeRenderer.cs @@ -27,6 +27,16 @@ internal class SystemButtonDarkModeRenderer : ButtonDarkModeRendererBase private protected override Padding PaddingCore { get; } = new Padding(SystemStylePadding); + private protected override GraphicsPath? CreateBackgroundPath(Rectangle bounds, bool isDefault, bool focused) + { + if (bounds.Width <= 0 || bounds.Height <= 0) + { + return null; + } + + return CreateRoundedPath(GetPathBounds(bounds), CornerRadius - DarkBorderGapThickness); + } + /// /// Draws button background with system styling (larger rounded corners). /// @@ -38,17 +48,26 @@ public override Rectangle DrawButtonBackground( bool focused, Color backColor) { - // Shrink for DarkBorderGap and FocusBorderThickness - Rectangle fillBounds = Rectangle.Inflate(bounds, -SystemStylePadding, -SystemStylePadding); - - using GraphicsPath fillPath = CreateRoundedRectanglePath(fillBounds, CornerRadius - DarkBorderGapThickness); + GraphicsState? saved = graphics.Save(); + try + { + graphics.SmoothingMode = SmoothingMode.AntiAlias; - // Fill the background using cached brush - using var brush = backColor.GetCachedSolidBrushScope(); - graphics.FillPath(brush, fillPath); + RectangleF pathBounds = GetPathBounds(bounds); + using GraphicsPath fillPath = CreateRoundedPath(pathBounds, FocusIndicatorCornerRadius); + using var brush = backColor.GetCachedSolidBrushScope(); + graphics.FillPath(brush, fillPath); + } + finally + { + if (saved is not null) + { + graphics.Restore(saved); + } + } // Return content bounds (area inside the button for text/image) - return fillBounds; + return bounds; } /// @@ -56,20 +75,28 @@ public override Rectangle DrawButtonBackground( /// public override void DrawFocusIndicator(Graphics graphics, Rectangle contentBounds, bool isDefault) { - // We need the bottom and the right border one pixel inside the button - Rectangle focusRect = new( - x: contentBounds.X, - y: contentBounds.Y, - width: contentBounds.Width - 1, - height: contentBounds.Height - 1); - - // Create path for the focus outline - using GraphicsPath focusPath = CreateRoundedRectanglePath(focusRect, FocusIndicatorCornerRadius); - - // System style uses a solid white border instead of dotted lines - using var focusPen = Color.White.GetCachedPenScope(FocusedButtonBorderThickness); + GraphicsState? saved = graphics.Save(); + try + { + graphics.SmoothingMode = SmoothingMode.AntiAlias; - graphics.DrawPath(focusPen, focusPath); + RectangleF outerBounds = GetPathBounds(contentBounds); + float outerRadius = FocusIndicatorCornerRadius + (2 * SystemStylePadding); + Color focusColor = ResolveBorderColor(Color.White); + using var focusBrush = focusColor.GetCachedSolidBrushScope(); + using GraphicsPath focusPath = CreateRingPath( + outerBounds, + outerRadius, + FocusedButtonBorderThickness); + graphics.FillPath(focusBrush, focusPath); + } + finally + { + if (saved is not null) + { + graphics.Restore(saved); + } + } } /// @@ -139,7 +166,9 @@ public void DrawButtonBorder( // Outer border path Rectangle borderRect = Rectangle.Inflate(bounds, -SystemStylePadding, -SystemStylePadding); - using GraphicsPath borderPath = CreateRoundedRectanglePath(borderRect, CornerRadius); + using GraphicsPath borderPath = CreateRoundedPath( + GetPathBounds(borderRect), + CornerRadius); // We need to implement a subtle 3d effect around the already // painted filling. We do this by drawing a border with a 1px pen, @@ -274,15 +303,39 @@ private static GraphicsPath GetBottomRightSegmentPath(Rectangle bounds, int radi return path; } - /// - /// Creates a GraphicsPath for a rounded rectangle. - /// - private static GraphicsPath CreateRoundedRectanglePath(Rectangle bounds, int radius) + private static RectangleF GetPathBounds(Rectangle bounds) + => new( + bounds.X, + bounds.Y, + Math.Max(1, bounds.Width - 1), + Math.Max(1, bounds.Height - 1)); + + private static RectangleF Inset(RectangleF bounds, float inset) + => new( + bounds.X + inset, + bounds.Y + inset, + Math.Max(1, bounds.Width - (2 * inset)), + Math.Max(1, bounds.Height - (2 * inset))); + + private static GraphicsPath CreateRoundedPath(RectangleF bounds, float radius) { GraphicsPath path = new(); + float clampedRadius = Math.Clamp(radius, 1, Math.Min(bounds.Width, bounds.Height)); + path.AddRoundedRectangle(bounds, new SizeF(clampedRadius, clampedRadius)); + return path; + } - path.AddRoundedRectangle(bounds, new Size(radius, radius)); - + private static GraphicsPath CreateRingPath( + RectangleF outerBounds, + float outerRadius, + float thickness) + { + GraphicsPath path = CreateRoundedPath(outerBounds, outerRadius); + RectangleF innerBounds = Inset(outerBounds, thickness); + float innerRadius = Math.Max(1, outerRadius - (2 * thickness)); + using GraphicsPath innerPath = CreateRoundedPath(innerBounds, innerRadius); + path.FillMode = FillMode.Alternate; + path.AddPath(innerPath, connect: false); return path; } } diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/CheckBox.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/CheckBox.cs index 690df74093e..58304272e9b 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/CheckBox.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/CheckBox.cs @@ -348,6 +348,12 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) return Rendering.CheckBox.ToggleSwitchMetrics.Create(this).GetPreferredSize(this); } + if (Appearance == Appearance.Button && FlatStyle == FlatStyle.Popup) + { + return DarkModeAdapterFactory.CreatePopupAdapter(this).GetPreferredSizeCore(proposedConstraints) + + Padding.Size; + } + if (Appearance == Appearance.Button) { ButtonStandardAdapter adapter = new(this); diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/RadioButton.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/RadioButton.cs index 48946e1dd7d..81bec289917 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/RadioButton.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/Buttons/RadioButton.cs @@ -288,6 +288,12 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) return Rendering.CheckBox.ToggleSwitchMetrics.Create(this).GetPreferredSize(this); } + if (Appearance == Appearance.Button && FlatStyle == FlatStyle.Popup) + { + return DarkModeAdapterFactory.CreatePopupAdapter(this).GetPreferredSizeCore(proposedConstraints) + + Padding.Size; + } + if (FlatStyle != FlatStyle.System) { return base.GetPreferredSizeCore(proposedConstraints); diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/RichTextBox/RichTextBox.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/RichTextBox/RichTextBox.cs index 4b4fa46bee1..7155719eb48 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/RichTextBox/RichTextBox.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/RichTextBox/RichTextBox.cs @@ -328,10 +328,25 @@ protected override CreateParams CreateParams /// /// RichEdit reserves the scrollbar space itself while processing WM_NCCALCSIZE (see - /// ), so no additional managed scrollbar allowance is - /// added on top; otherwise the space would be counted twice. + /// ). Return the configured reservation for preferred-size + /// measurement; the native client-area calculation explicitly excludes it. /// - private protected override Padding GetScrollBarPadding() => Padding.Empty; + private protected override Padding GetScrollBarPadding() + { + Padding padding = Padding.Empty; + + if (Multiline && !WordWrap && (ScrollBars & RichTextBoxScrollBars.Horizontal) != 0) + { + padding.Bottom = SystemInformation.GetHorizontalScrollBarHeightForDpi(DeviceDpiInternal); + } + + if (Multiline && (ScrollBars & RichTextBoxScrollBars.Vertical) != 0) + { + padding.Right = SystemInformation.GetVerticalScrollBarWidthForDpi(DeviceDpiInternal); + } + + return padding; + } /// /// Controls whether or not the rich edit control will automatically highlight URLs. @@ -437,6 +452,12 @@ public override Font Font internal override Size GetPreferredSizeCore(Size proposedConstraints) { + if (EffectiveVisualStylesMode >= VisualStylesMode.Net11) + { + // TextBoxBase owns the modern inset, user Padding, and scrollbar geometry. + return base.GetPreferredSizeCore(proposedConstraints); + } + Size scrollBarPadding = Size.Empty; // If the RTB is multiline, we won't have a horizontal scrollbar. @@ -657,6 +678,7 @@ public RichTextBoxScrollBars ScrollBars using (LayoutTransaction.CreateTransactionIf(AutoSize, ParentInternal, this, PropertyNames.ScrollBars)) { _richTextBoxFlags[s_scrollBarsSection] = (int)value; + CommonProperties.xClearPreferredSizeCache(this); RecreateHandle(); } } diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/MaskedTextBox.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/MaskedTextBox.cs index d0670ce3e1f..08c4fd56f9a 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/MaskedTextBox.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/MaskedTextBox.cs @@ -2884,7 +2884,9 @@ private void WmPrint(ref Message m) { base.WndProc(ref m); if (((nint)m.LParamInternal & PInvoke.PRF_NONCLIENT) != 0 - && Application.RenderWithVisualStyles && BorderStyle == BorderStyle.Fixed3D) + && Application.RenderWithVisualStyles + && BorderStyle == BorderStyle.Fixed3D + && EffectiveVisualStylesMode < VisualStylesMode.Net11) { using Graphics g = Graphics.FromHdc((HDC)m.WParamInternal); Rectangle rect = new(0, 0, Size.Width - 1, Size.Height - 1); diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/TextBox.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/TextBox.cs index 50299a05186..5f29b798482 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/TextBox.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/TextBox.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.Drawing; using System.Drawing.Design; +using System.Windows.Forms.Layout; using System.Windows.Forms.VisualStyles; using Windows.Win32.UI.Accessibility; @@ -383,6 +384,8 @@ public ScrollBars ScrollBars _scrollBars = value; RecreateHandle(); + CommonProperties.xClearPreferredSizeCache(this); + LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.ScrollBars); } } } @@ -391,6 +394,13 @@ public ScrollBars ScrollBars internal override Size GetPreferredSizeCore(Size proposedConstraints) { + if (EffectiveVisualStylesMode >= VisualStylesMode.Net11) + { + // TextBoxBase already includes the native scrollbar reservation in the modern geometry. + // Applying the legacy adjustment here would count each scrollbar twice. + return base.GetPreferredSizeCore(proposedConstraints); + } + Size scrollBarPadding = Size.Empty; if (Multiline && !WordWrap && (ScrollBars & ScrollBars.Horizontal) != 0) @@ -411,6 +421,31 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) return prefSize + scrollBarPadding; } + private protected override Padding GetScrollBarPadding() + { + if (IsHandleCreated) + { + return base.GetScrollBarPadding(); + } + + Padding padding = Padding.Empty; + + if (Multiline + && !WordWrap + && _textAlign == HorizontalAlignment.Left + && (_scrollBars & ScrollBars.Horizontal) != 0) + { + padding.Bottom = SystemInformation.GetHorizontalScrollBarHeightForDpi(DeviceDpiInternal); + } + + if (Multiline && (_scrollBars & ScrollBars.Vertical) != 0) + { + padding.Right = SystemInformation.GetVerticalScrollBarWidthForDpi(DeviceDpiInternal); + } + + return padding; + } + /// /// Gets or sets the current text in the text box. /// diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs index 6055fea74c2..6028fa0a6a7 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/TextBox/TextBoxBase.cs @@ -57,6 +57,8 @@ public abstract partial class TextBoxBase : Control private const int VisualStylesFixed3DBorderPadding = 5; private const int VisualStylesFixedSingleBorderPadding = 4; private const int VisualStylesNoBorderPadding = 3; + internal const int VisualStylesInternalChromeInset = 2; + private const int VisualStylesCornerRadius = 15; private const int BorderThickness = 1; /// @@ -360,8 +362,21 @@ public BorderStyle BorderStyle SourceGenerated.EnumValidator.Validate(value); _borderStyle = value; + CommonProperties.xClearPreferredSizeCache(this); + if (EffectiveVisualStylesMode >= VisualStylesMode.Net11) + { + AdjustHeight(false); + } + UpdateStyles(); - RecreateHandle(); + if (EffectiveVisualStylesMode >= VisualStylesMode.Net11 && IsHandleCreated) + { + RecalculateVisualStylesClientArea(); + } + else + { + RecreateHandle(); + } // PreferredSize depends on BorderStyle : thru CreateParams.ExStyle in User32!AdjustRectEx. // So when the BorderStyle changes let the parent of this control know about it. @@ -853,8 +868,25 @@ private void ResetPadding() /// Returns the preferred height for modern Visual Styles, taking the carved padding band /// (including the live scrollbar allowance and the user ) into account. /// - private protected virtual int PreferredHeightCore => - FontHeight + GetVisualStylesPadding(includeScrollbars: true).Vertical; + private protected virtual int PreferredHeightCore + { + get + { + int preferredHeight = FontHeight + GetVisualStylesPadding(includeScrollbars: true).Vertical; + + if (AutoSize && !Multiline && BorderStyle == BorderStyle.Fixed3D) + { + // A naturally sized single-line control must leave enough room for the complete + // rounded chrome. Explicitly fixed controls are not forced through this floor. + int roundedChromeMinimumHeight = (ScaleVisualStylesMetric(VisualStylesCornerRadius) * 2) + + ScaleVisualStylesMetric(BorderThickness) + + ScaleVisualStylesMetric(VisualStylesInternalChromeInset); + preferredHeight = Math.Max(preferredHeight, roundedChromeMinimumHeight); + } + + return preferredHeight; + } + } /// /// Returns the classic (Everett-compatible) preferred height for a single-line text box. @@ -891,12 +923,13 @@ private int PreferredHeightClassic /// /// /// The visible part of the padding is the area by which we extend the real-estate of the control - /// with its back color. The user-provided is always added on top. + /// with its back color. Border/corner reservation, the DPI-scaled internal chrome inset, the + /// user-provided , and scrollbar reservation are each added once. /// /// private protected Padding GetVisualStylesPadding(bool includeScrollbars) { - int offset = LogicalToDeviceUnits(BorderThickness); + int offset = ScaleVisualStylesMetric(BorderThickness); // The visible padding is selected per BorderStyle (not per VisualStylesMode): each border look // reserves a differently sized band around the native edit's client area for the modern chrome @@ -905,30 +938,32 @@ private protected Padding GetVisualStylesPadding(bool includeScrollbars) // single-line border; None reserves only a minimal band, plus extra room on the right and bottom // for the scrollbars and the focus line. BorderThickness (offset) is added so the drawn border // line sits inside the reserved band rather than on its outer edge. - Padding padding = BorderStyle switch + Padding borderPadding = BorderStyle switch { BorderStyle.Fixed3D => new Padding( - left: LogicalToDeviceUnits(VisualStylesFixed3DBorderPadding) + offset, - top: LogicalToDeviceUnits(VisualStylesFixed3DBorderPadding) + offset, - right: LogicalToDeviceUnits(VisualStylesFixed3DBorderPadding) + offset, - bottom: LogicalToDeviceUnits(VisualStylesFixed3DBorderPadding) + offset), + left: ScaleVisualStylesMetric(VisualStylesFixed3DBorderPadding) + offset, + top: ScaleVisualStylesMetric(VisualStylesFixed3DBorderPadding) + offset, + right: ScaleVisualStylesMetric(VisualStylesFixed3DBorderPadding) + offset, + bottom: ScaleVisualStylesMetric(VisualStylesFixed3DBorderPadding) + offset), BorderStyle.FixedSingle => new Padding( - left: LogicalToDeviceUnits(VisualStylesFixedSingleBorderPadding) + offset, - top: LogicalToDeviceUnits(VisualStylesFixedSingleBorderPadding) + offset, - right: LogicalToDeviceUnits(VisualStylesFixedSingleBorderPadding) + offset, - bottom: LogicalToDeviceUnits(VisualStylesFixedSingleBorderPadding) + offset), + left: ScaleVisualStylesMetric(VisualStylesFixedSingleBorderPadding) + offset, + top: ScaleVisualStylesMetric(VisualStylesFixedSingleBorderPadding) + offset, + right: ScaleVisualStylesMetric(VisualStylesFixedSingleBorderPadding) + offset, + bottom: ScaleVisualStylesMetric(VisualStylesFixedSingleBorderPadding) + offset), BorderStyle.None => new Padding( - left: LogicalToDeviceUnits(VisualStylesNoBorderPadding), - top: LogicalToDeviceUnits(VisualStylesNoBorderPadding), - right: LogicalToDeviceUnits(VisualStylesNoBorderPadding) + offset, + left: ScaleVisualStylesMetric(VisualStylesNoBorderPadding), + top: ScaleVisualStylesMetric(VisualStylesNoBorderPadding), + right: ScaleVisualStylesMetric(VisualStylesNoBorderPadding) + offset, // We still need some extra space for the focus indication. - bottom: LogicalToDeviceUnits(VisualStylesNoBorderPadding) + offset), + bottom: ScaleVisualStylesMetric(VisualStylesNoBorderPadding) + offset), _ => Padding.Empty, }; + Padding padding = borderPadding + new Padding(ScaleVisualStylesMetric(VisualStylesInternalChromeInset)); + if (includeScrollbars) { padding += GetScrollBarPadding(); @@ -939,6 +974,9 @@ private protected Padding GetVisualStylesPadding(bool includeScrollbars) return padding; } + private int ScaleVisualStylesMetric(int logicalValue) + => ScaleHelper.ScaleToDpi(logicalValue, DeviceDpiInternal); + /// /// Returns the additional padding required to clear the live scrollbars, /// if any are currently shown. @@ -1613,6 +1651,8 @@ protected override void OnHandleCreated(EventArgs e) ScrollToCaret(); _textBoxFlags[s_scrollToCaretOnHandleCreated] = false; } + + RecalculateVisualStylesClientArea(); } protected override void OnHandleDestroyed(EventArgs e) @@ -1624,6 +1664,27 @@ protected override void OnHandleDestroyed(EventArgs e) base.OnHandleDestroyed(e); } + /// + protected override void OnVisualStylesModeChanged(EventArgs e) + { + base.OnVisualStylesModeChanged(e); + + CommonProperties.xClearPreferredSizeCache(this); + LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.VisualStylesMode); + AdjustHeight(false); + + if (!IsHandleCreated) + { + return; + } + + // Update the native styles without recreating the handle so text, selection, and scroll state + // remain untouched. The client-area latch must be reset before requesting a new frame. + _triggerNewClientSizeRequest = false; + UpdateStyles(); + RecalculateVisualStylesClientArea(); + } + /// /// Replaces the current selection in the text box with the contents of the Clipboard. /// @@ -1719,9 +1780,25 @@ protected override unsafe void OnSizeChanged(EventArgs e) protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); + CommonProperties.xClearPreferredSizeCache(this); + LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.Font); AdjustHeight(false); } + protected override void OnDpiChangedAfterParent(EventArgs e) + { + base.OnDpiChangedAfterParent(e); + + CommonProperties.xClearPreferredSizeCache(this); + LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.Bounds); + AdjustHeight(false); + + if (EffectiveVisualStylesMode >= VisualStylesMode.Net11) + { + RecalculateVisualStylesClientArea(); + } + } + protected virtual void OnHideSelectionChanged(EventArgs e) { if (Events[s_hideSelectionChangedEvent] is EventHandler eh) @@ -1778,6 +1855,8 @@ protected virtual void OnMultilineChanged(EventArgs e) protected override void OnPaddingChanged(EventArgs e) { base.OnPaddingChanged(e); + CommonProperties.xClearPreferredSizeCache(this); + LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.Padding); AdjustHeight(false); // The carved modern Visual Styles padding band includes the user Padding, so a runtime change @@ -2339,14 +2418,14 @@ private unsafe void WmNcCalcSize(ref Message m) // Controls whose native window reserves its own non-client metrics (RichEdit reserves its // border and scrollbars) must run the default handler first, so we carve the modern padding // band from the already-adjusted client rectangle rather than the raw proposed window - // rectangle. Those controls report an empty GetScrollBarPadding so the scrollbar space the - // native handler already reserved is not counted twice. + // rectangle. Their managed scrollbar allowance is omitted from this carve because the + // native handler already reserved it. if (ReservesNativeNonClientArea) { base.WndProc(ref m); } - Padding padding = GetVisualStylesPadding(includeScrollbars: true); + Padding padding = GetVisualStylesPadding(includeScrollbars: !ReservesNativeNonClientArea); ref RECT clientRect = ref ncCalcSizeParams->rgrc._0; @@ -2429,6 +2508,26 @@ private void WmNcPaint(ref Message m) } } + private void WmPrint(ref Message m) + { + base.WndProc(ref m); + + if (EffectiveVisualStylesMode < VisualStylesMode.Net11 + || ((nint)m.LParamInternal & PInvoke.PRF_NONCLIENT) == 0) + { + return; + } + + HDC hdc = (HDC)m.WParamInternal; + if (hdc.IsNull) + { + return; + } + + using Graphics graphics = Graphics.FromHdc(hdc); + OnNcPaint(graphics, hdc); + } + /// /// Builds a non-client update region, in screen coordinates, that spans the whole window but /// excludes the live client rectangle. This is handed to the default WM_NCPAINT handler so @@ -2473,8 +2572,8 @@ private RegionScope CreateNonClientClipRegion() /// private protected virtual void OnNcPaint(Graphics graphics, HDC windowHdc) { - int cornerRadius = LogicalToDeviceUnits(15); - int borderThickness = LogicalToDeviceUnits(BorderThickness); + int cornerRadius = ScaleVisualStylesMetric(VisualStylesCornerRadius); + int borderThickness = ScaleVisualStylesMetric(BorderThickness); Color adornerColor = ForeColor; @@ -2498,17 +2597,10 @@ private protected virtual void OnNcPaint(Graphics graphics, HDC windowHdc) width: Bounds.Width, height: Bounds.Height); - Padding clientPadding = GetVisualStylesPadding(includeScrollbars: false); - - // This is the client area without the padding. - Rectangle clientBounds = new( - clientPadding.Left, - clientPadding.Top, - Math.Max(0, bounds.Width - clientPadding.Horizontal), - Math.Max(0, bounds.Height - clientPadding.Vertical)); - clientBounds = Rectangle.Intersect(bounds, clientBounds); + // The native client rectangle is the only protected area. It includes the border, internal + // chrome inset, user Padding, and scrollbar reservation exactly as the native window reports it. + Rectangle clientBounds = Rectangle.Intersect(bounds, GetNativeClientRectangle()); - // This is the client area of the actual original edit control. Rectangle deflatedBounds = bounds; // Making sure we never color outside the lines. @@ -2535,14 +2627,22 @@ private protected virtual void OnNcPaint(Graphics graphics, HDC windowHdc) bounds.Inflate(1, 1); - // Fill the buffer with the parent background color. - offscreenGraphics.FillRectangle(parentBackgroundBrush, bounds); - // Below roughly 2 * cornerRadius + thickness the rounded Fixed3D chrome renders as a broken // lozenge. When the available height is below that viable threshold we fall back to flat/simple // chrome. This is a render-only fallback - it does not change size, layout, or ClientSize. bool canRenderRoundedChrome = deflatedBounds.Height >= (2 * cornerRadius) + borderThickness; + if (BorderStyle == BorderStyle.Fixed3D && canRenderRoundedChrome) + { + using GraphicsPath roundedBodyPath = new(); + roundedBodyPath.AddRoundedRectangle(deflatedBounds, new Size(cornerRadius, cornerRadius)); + ParentBackgroundRenderer.Paint(this, offscreenGraphics, bufferBounds, roundedBodyPath, parentBackColor); + } + else + { + offscreenGraphics.FillRectangle(parentBackgroundBrush, bounds); + } + switch (BorderStyle) { case BorderStyle.None: @@ -2680,6 +2780,25 @@ private static Rectangle[] GetNonClientPaintBands(Rectangle bounds, Rectangle cl ]; } + private Rectangle GetNativeClientRectangle() + { + if (!IsHandleCreated + || !PInvokeCore.GetWindowRect(this, out RECT windowRect)) + { + return Rectangle.Empty; + } + + PInvokeCore.GetClientRect(this, out RECT clientRect); + Point clientTopLeft = default; + PInvoke.ClientToScreen(this, ref clientTopLeft); + + return new Rectangle( + clientTopLeft.X - windowRect.left, + clientTopLeft.Y - windowRect.top, + clientRect.Width, + clientRect.Height); + } + private void WmReflectCommand(ref Message m) { if (_textBoxFlags[s_codeUpdateText] || _textBoxFlags[s_creatingHandle]) @@ -2767,6 +2886,9 @@ protected override void WndProc(ref Message m) case PInvokeCore.WM_NCPAINT: WmNcPaint(ref m); break; + case PInvokeCore.WM_PRINT: + WmPrint(ref m); + break; case PInvokeCore.WM_LBUTTONDBLCLK: _doubleClickFired = true; diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/DomainUpDown.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/DomainUpDown.cs index 70f700fe3b7..7aac9b4c3d3 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/DomainUpDown.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/DomainUpDown.cs @@ -512,7 +512,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) int width = LayoutUtils.OldGetLargestStringSizeInCollection(Font, Items).Width; // AdjustWindowRect with our border, since textbox is borderless. - width = SizeFromClientSizeInternal(new(width, height)).Width + _upDownButtons.Width; + width = GetPreferredWidth(width, height); return new Size(width, height) + Padding.Size; } } diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/NumericUpDown.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/NumericUpDown.cs index fd1695e47f6..6c6e5516735 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/NumericUpDown.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/NumericUpDown.cs @@ -822,7 +822,7 @@ internal override Size GetPreferredSizeCore(Size proposedConstraints) } // Call AdjustWindowRect to add space for the borders - int width = SizeFromClientSizeInternal(new(textWidth, height)).Width + _upDownButtons.Width; + int width = GetPreferredWidth(textWidth, height); return new Size(width, height) + Padding.Size; } diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/UpDownBase.UpDownButtons.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/UpDownBase.UpDownButtons.cs index f85e0337970..726ae729253 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/UpDownBase.UpDownButtons.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/UpDownBase.UpDownButtons.cs @@ -72,9 +72,15 @@ internal Rectangle GetButtonRectangle(ButtonID button) if (UseSideBySideButtons) { - int half = client.Width / 2; - Rectangle leadingRect = new(client.X, client.Y, half, client.Height); - Rectangle trailingRect = new(client.X + half, client.Y, client.Width - half, client.Height); + int spacing = Math.Min(_parent.ModernButtonGroupSpacing, client.Width); + int availableWidth = Math.Max(0, client.Width - spacing); + int leadingWidth = (availableWidth + 1) / 2; + Rectangle leadingRect = new(client.X, client.Y, leadingWidth, client.Height); + Rectangle trailingRect = new( + client.X + leadingWidth + spacing, + client.Y, + availableWidth - leadingWidth, + client.Height); bool rightToLeft = _parent.RightToLeft == RightToLeft.Yes; Rectangle upRect = rightToLeft ? leadingRect : trailingRect; @@ -96,9 +102,18 @@ internal Rectangle GetButtonRectangle(ButtonID button) /// The mouse event arguments. private void BeginButtonPress(MouseEventArgs e) { - _pushed = _captured = GetButtonRectangle(ButtonID.Up).Contains(e.Location) + ButtonID button = GetButtonRectangle(ButtonID.Up).Contains(e.Location) ? ButtonID.Up - : ButtonID.Down; + : GetButtonRectangle(ButtonID.Down).Contains(e.Location) + ? ButtonID.Down + : ButtonID.None; + + if (button == ButtonID.None) + { + return; + } + + _pushed = _captured = button; Invalidate(); // Capture the mouse @@ -212,14 +227,15 @@ protected override void OnMouseMove(MouseEventArgs e) Rectangle rectDown = GetButtonRectangle(ButtonID.Down); // Check if the mouse is on the upper or lower button. Note that it could be in neither. - if (rectUp.Contains(e.X, e.Y)) - { - _mouseOver = ButtonID.Up; - Invalidate(); - } - else if (rectDown.Contains(e.X, e.Y)) + ButtonID mouseOver = rectUp.Contains(e.X, e.Y) + ? ButtonID.Up + : rectDown.Contains(e.X, e.Y) + ? ButtonID.Down + : ButtonID.None; + + if (_mouseOver != mouseOver) { - _mouseOver = ButtonID.Down; + _mouseOver = mouseOver; Invalidate(); } @@ -296,27 +312,41 @@ protected override void OnPaint(PaintEventArgs e) // the modern control-button renderer, which adapts to both light and dark modes. bool isDarkMode = Application.IsDarkModeEnabled; - Graphics cachedGraphics = EnsureCachedBitmap(ClientSize.Width, ClientSize.Height); + using Graphics cachedGraphics = EnsureCachedBitmap(ClientSize.Width, ClientSize.Height); DrawModernControlButton( cachedGraphics, GetButtonRectangle(ButtonID.Down), - ModernControlButtonStyle.Down | ModernControlButtonStyle.SingleBorder, + ModernControlButtonStyle.Down, GetButtonState(ButtonID.Down), isDarkMode); DrawModernControlButton( cachedGraphics, GetButtonRectangle(ButtonID.Up), - ModernControlButtonStyle.Up | ModernControlButtonStyle.SingleBorder, + ModernControlButtonStyle.Up, GetButtonState(ButtonID.Up), isDarkMode); e.GraphicsInternal.DrawImageUnscaled(_cachedBitmap, new Point(0, 0)); + + int spacing = _parent.ModernButtonGroupSpacing; + if (spacing > 0) + { + Rectangle upBounds = GetButtonRectangle(ButtonID.Up); + Rectangle downBounds = GetButtonRectangle(ButtonID.Down); + Rectangle gap = new( + Math.Min(upBounds.Right, downBounds.Right), + 0, + spacing, + ClientSize.Height); + using var gapBrush = _parent.BackColor.GetCachedSolidBrushScope(); + e.Graphics.FillRectangle(gapBrush, gap); + } } else if (Application.IsDarkModeEnabled) { - Graphics cachedGraphics = EnsureCachedBitmap( + using Graphics cachedGraphics = EnsureCachedBitmap( _parent._defaultButtonsWidth, ClientSize.Height); diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/UpDownBase.UpDownEdit.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/UpDownBase.UpDownEdit.cs index bfdb45c17ef..8262d0f374a 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/UpDownBase.UpDownEdit.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/UpDownBase.UpDownEdit.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Drawing; using Windows.Win32.UI.Accessibility; namespace System.Windows.Forms; @@ -19,6 +20,18 @@ internal UpDownEdit(UpDownBase parent) _parent = parent; } + public override VisualStylesMode VisualStylesMode + { + get => VisualStylesMode.Classic; + set + { + } + } + + private protected override void OnNcPaint(Graphics graphics, HDC windowHdc) + { + } + [AllowNull] public override string Text { @@ -114,6 +127,7 @@ protected override void OnGotFocus(EventArgs e) { _parent.SetActiveControl(this); _parent.InvokeGotFocus(_parent, e); + _parent.Invalidate(); if (IsAccessibilityObjectCreated) { @@ -122,6 +136,9 @@ protected override void OnGotFocus(EventArgs e) } protected override void OnLostFocus(EventArgs e) - => _parent.InvokeLostFocus(_parent, e); + { + _parent.InvokeLostFocus(_parent, e); + _parent.Invalidate(); + } } } diff --git a/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/UpDownBase.cs b/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/UpDownBase.cs index 6da711535d2..e1c23e6f79a 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/UpDownBase.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Controls/UpDown/UpDownBase.cs @@ -5,6 +5,7 @@ using System.Drawing; using System.Drawing.Drawing2D; using System.Runtime.InteropServices; +using System.Windows.Forms.Layout; using System.Windows.Forms.VisualStyles; using Microsoft.Win32; @@ -21,14 +22,10 @@ public abstract partial class UpDownBase : ContainerControl private const int DefaultControlWidth = 120; private const int ThemedBorderWidth = 1; // width of custom border we draw when themed - // Modern (Net11+) chrome geometry, mirrored from TextBoxBase so the frame we draw around the - // whole control matches the look of a stand-alone modern TextBox. The padding values determine how - // far the edit and the buttons are inset from the outer edge so they clear the drawn border and the - // rounded corners; the border thickness and corner radius drive the frame itself. - private const int ModernFixed3DBorderPadding = 5; - private const int ModernFixedSingleBorderPadding = 4; - private const int ModernNoBorderPadding = 3; + // Modern (Net11+) chrome geometry. The edit and button group share the border thickness and + // internal chrome inset used by TextBoxBase; only the gap between the two buttons is additional. private const int ModernBorderThickness = 1; + private const int ModernButtonGroupSpacingLogical = 2; private const int ModernCornerRadius = 15; private const BorderStyle DefaultBorderStyle = BorderStyle.Fixed3D; private const LeftRightAlignment DefaultUpDownAlign = LeftRightAlignment.Right; @@ -353,6 +350,22 @@ public int PreferredHeight { get { + if (UseSideBySideButtons) + { + int contentInset = ModernContentInset; + int preferredHeight = FontHeight + (contentInset * 2); + + if (_borderStyle == BorderStyle.Fixed3D) + { + int roundedChromeMinimumHeight = (LogicalToDeviceUnits(ModernCornerRadius) * 2) + + LogicalToDeviceUnits(ModernBorderThickness) + + LogicalToDeviceUnits(TextBoxBase.VisualStylesInternalChromeInset); + preferredHeight = Math.Max(preferredHeight, roundedChromeMinimumHeight); + } + + return preferredHeight; + } + int height = FontHeight; // Adjust for the border style @@ -469,7 +482,13 @@ public LeftRightAlignment UpDownAlign internal override Rectangle ApplyBoundsConstraints(int suggestedX, int suggestedY, int proposedWidth, int proposedHeight) { - return base.ApplyBoundsConstraints(suggestedX, suggestedY, proposedWidth, PreferredHeight); + int height = AutoSize + ? PreferredHeight + Padding.Vertical + : UseSideBySideButtons + ? proposedHeight + : PreferredHeight; + + return base.ApplyBoundsConstraints(suggestedX, suggestedY, proposedWidth, height); } internal override void ReleaseUiaProvider(HWND handle) @@ -497,6 +516,14 @@ protected override void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNe base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); _defaultButtonsWidth = LogicalToDeviceUnits(DefaultButtonsWidth); _upDownButtons.Width = _defaultButtonsWidth; + CommonProperties.xClearPreferredSizeCache(this); + + if (AutoSize) + { + Height = PreferredHeight; + } + + PositionControls(); } /// @@ -525,6 +552,25 @@ protected override void OnHandleDestroyed(EventArgs e) base.OnHandleDestroyed(e); } + /// + protected override void OnVisualStylesModeChanged(EventArgs e) + { + base.OnVisualStylesModeChanged(e); + CommonProperties.xClearPreferredSizeCache(this); + + if (AutoSize) + { + Height = PreferredHeight; + } + + PositionControls(); + + if (IsHandleCreated) + { + Invalidate(true); + } + } + /// /// Handles painting the buttons on the control. /// @@ -663,7 +709,11 @@ protected virtual void OnTextBoxLostFocus(object? source, EventArgs e) /// protected virtual void OnTextBoxResize(object? source, EventArgs e) { - Height = PreferredHeight; + if (!UseSideBySideButtons || AutoSize) + { + Height = PreferredHeight; + } + PositionControls(); } @@ -828,7 +878,11 @@ protected override void OnFontChanged(EventArgs e) // Clear the font height cache FontHeight = -1; - Height = PreferredHeight; + if (!UseSideBySideButtons || AutoSize) + { + Height = PreferredHeight; + } + PositionControls(); base.OnFontChanged(e); @@ -865,8 +919,9 @@ private void PositionControls() Rectangle upDownEditBounds = Rectangle.Empty; Rectangle upDownButtonsBounds = Rectangle.Empty; - Rectangle clientArea = new(Point.Empty, ClientSize); - int totalClientWidth = clientArea.Width; + Rectangle clientArea = LayoutUtils.DeflateRect( + new Rectangle(Point.Empty, ClientSize), + Padding); bool themed = Application.RenderWithVisualStyles; BorderStyle borderStyle = BorderStyle; @@ -905,8 +960,8 @@ private void PositionControls() if (updownAlign == LeftRightAlignment.Left) { // If the buttons are aligned to the left, swap position of text box/buttons - upDownButtonsBounds.X = totalClientWidth - upDownButtonsBounds.Right; - upDownEditBounds.X = totalClientWidth - upDownEditBounds.Right; + upDownButtonsBounds.X = clientArea.Left + (clientArea.Right - upDownButtonsBounds.Right); + upDownEditBounds.X = clientArea.Left + (clientArea.Right - upDownEditBounds.Right); } // Apply locations @@ -919,35 +974,47 @@ private void PositionControls() } } - /// - /// The inset, in device units, of the edit and the buttons from the outer edge when a modern - /// is in effect. It matches the band a stand-alone modern TextBox - /// reserves for its border so the frame we draw in looks consistent and the - /// child controls clear the rounded corners. - /// - private int ModernBorderPadding => LogicalToDeviceUnits(_borderStyle switch - { - BorderStyle.Fixed3D => ModernFixed3DBorderPadding + ModernBorderThickness, - BorderStyle.FixedSingle => ModernFixedSingleBorderPadding + ModernBorderThickness, - _ => ModernNoBorderPadding, - }); + private int ModernContentInset + => LogicalToDeviceUnits( + (_borderStyle == BorderStyle.None ? 0 : ModernBorderThickness) + + TextBoxBase.VisualStylesInternalChromeInset); + + internal int ModernButtonGroupSpacing + => LogicalToDeviceUnits(ModernButtonGroupSpacingLogical); + + internal int GetModernButtonGroupWidth() + => (_defaultButtonsWidth * 2) + ModernButtonGroupSpacing; + + internal int GetPreferredWidth(int textWidth, int height) + => UseSideBySideButtons + ? textWidth + (ModernContentInset * 2) + GetModernButtonGroupWidth() + : SizeFromClientSizeInternal(new(textWidth, height)).Width + _upDownButtons.Width; /// /// Calculates the size and position of the upDownEdit control and the side-by-side updown buttons /// when a modern is in effect. Both the edit and the buttons are - /// inset by so they sit inside the frame drawn by + /// inset by so they sit inside the frame drawn by /// and clear its rounded corners. /// private void PositionControlsModern() { - Rectangle clientArea = new(Point.Empty, ClientSize); - int totalClientWidth = clientArea.Width; + Rectangle clientArea = LayoutUtils.DeflateRect( + new Rectangle(Point.Empty, ClientSize), + Padding); - int pad = ModernBorderPadding; - int buttonsWidth = _defaultButtonsWidth * 2; + int pad = ModernContentInset; + int buttonsWidth = Math.Min(GetModernButtonGroupWidth(), Math.Max(0, clientArea.Width - (pad * 2))); Rectangle inner = clientArea; inner.Inflate(-pad, -pad); + if (inner.Width < 0 || inner.Height < 0) + { + inner = new Rectangle( + x: Math.Min(pad, clientArea.Width), + y: Math.Min(pad, clientArea.Height), + width: 0, + height: 0); + } Rectangle upDownEditBounds = inner; upDownEditBounds.Width = Math.Max(0, inner.Width - buttonsWidth); @@ -961,8 +1028,8 @@ private void PositionControlsModern() // Left/right updown align translation (also honors RTL). if (RtlTranslateLeftRight(UpDownAlign) == LeftRightAlignment.Left) { - upDownButtonsBounds.X = totalClientWidth - upDownButtonsBounds.Right; - upDownEditBounds.X = totalClientWidth - upDownEditBounds.Right; + upDownButtonsBounds.X = clientArea.Left + (clientArea.Right - upDownButtonsBounds.Right); + upDownEditBounds.X = clientArea.Left + (clientArea.Right - upDownEditBounds.Right); } _upDownEdit?.Bounds = upDownEditBounds; @@ -995,7 +1062,6 @@ private void DrawModernBorder(PaintEventArgs e) Color parentBackColor = Parent?.BackColor ?? BackColor; Color clientBackColor = BackColor; - using var parentBackgroundBrush = parentBackColor.GetCachedSolidBrushScope(); using var clientBackgroundBrush = clientBackColor.GetCachedSolidBrushScope(); using var adornerPen = adornerColor.GetCachedPenScope(borderThickness); @@ -1004,15 +1070,25 @@ private void DrawModernBorder(PaintEventArgs e) deflatedBounds.Height -= 1; Graphics graphics = e.Graphics; + using GraphicsStateScope graphicsState = new(graphics); graphics.SmoothingMode = SmoothingMode.AntiAlias; - // Fill the whole client with the parent's back color; the rounded corners then blend against it. - graphics.FillRectangle(parentBackgroundBrush, bounds); - // Below roughly 2 * cornerRadius + thickness the rounded chrome renders as a broken lozenge; fall - // back to a flat rectangle in that case. This mirrors TextBoxBase.OnNcPaint. + // back to a flat rectangle in that case. bool canRenderRoundedChrome = deflatedBounds.Height >= (2 * cornerRadius) + borderThickness; + using GraphicsPath bodyPath = new(); + if (canRenderRoundedChrome) + { + bodyPath.AddRoundedRectangle(deflatedBounds, new Size(cornerRadius, cornerRadius)); + } + else + { + bodyPath.AddRectangle(deflatedBounds); + } + + ParentBackgroundRenderer.Paint(this, graphics, bounds, bodyPath, parentBackColor); + switch (_borderStyle) { case BorderStyle.None: @@ -1039,6 +1115,48 @@ private void DrawModernBorder(PaintEventArgs e) break; } + + if (Focused && _borderStyle == BorderStyle.Fixed3D) + { + using var focusPen = SystemColors.MenuHighlight.GetCachedPenScope(borderThickness); + if (canRenderRoundedChrome) + { + int focusInset = Math.Max(1, (cornerRadius - 3) / 2); + graphics.DrawLine( + focusPen, + deflatedBounds.Left + focusInset, + deflatedBounds.Bottom, + deflatedBounds.Right - focusInset, + deflatedBounds.Bottom); + graphics.DrawLine( + focusPen, + deflatedBounds.Left + focusInset - 2, + deflatedBounds.Bottom - 1, + deflatedBounds.Right - focusInset + 2, + deflatedBounds.Bottom - 1); + graphics.DrawLine( + focusPen, + deflatedBounds.Left + focusInset - 3, + deflatedBounds.Bottom - 2, + deflatedBounds.Right - focusInset + 3, + deflatedBounds.Bottom - 2); + } + else + { + graphics.DrawLine( + focusPen, + deflatedBounds.Left, + deflatedBounds.Bottom, + deflatedBounds.Right, + deflatedBounds.Bottom); + graphics.DrawLine( + focusPen, + deflatedBounds.Left, + deflatedBounds.Bottom - 1, + deflatedBounds.Right, + deflatedBounds.Bottom - 1); + } + } } /// diff --git a/src/System.Windows.Forms/System/Windows/Forms/ParentBackgroundRenderer.cs b/src/System.Windows.Forms/System/Windows/Forms/ParentBackgroundRenderer.cs new file mode 100644 index 00000000000..234ff9e7644 --- /dev/null +++ b/src/System.Windows.Forms/System/Windows/Forms/ParentBackgroundRenderer.cs @@ -0,0 +1,42 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Drawing; +using System.Drawing.Drawing2D; + +namespace System.Windows.Forms; + +internal static class ParentBackgroundRenderer +{ + internal static void Paint( + Control control, + Graphics graphics, + Rectangle bounds, + GraphicsPath opaquePath, + Color fallbackColor) + { + ArgumentNullException.ThrowIfNull(control); + ArgumentNullException.ThrowIfNull(graphics); + ArgumentNullException.ThrowIfNull(opaquePath); + + using GraphicsStateScope state = new(graphics); + using Region exposedRegion = new(bounds); + exposedRegion.Exclude(opaquePath); + + // Keep an existing clip (for example, the native TextBox client area) in effect while + // PaintTransparentBackground establishes the parent-coordinate clip. + using Region currentClip = graphics.Clip; + exposedRegion.Intersect(currentClip); + + Control? parent = control.ParentInternal; + if (parent is null || parent.IsDisposed) + { + using SolidBrush fallbackBrush = new(fallbackColor); + graphics.FillRegion(fallbackBrush, exposedRegion); + return; + } + + using PaintEventArgs paintEventArgs = new(graphics, bounds); + control.PaintTransparentBackground(paintEventArgs, bounds, exposedRegion); + } +} diff --git a/src/System.Windows.Forms/System/Windows/Forms/Rendering/Button/AnimatedPopupButtonRenderer.cs b/src/System.Windows.Forms/System/Windows/Forms/Rendering/Button/AnimatedPopupButtonRenderer.cs index b930efbefe2..573e0f4aa04 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Rendering/Button/AnimatedPopupButtonRenderer.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Rendering/Button/AnimatedPopupButtonRenderer.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Drawing; +using System.Drawing.Drawing2D; using System.Windows.Forms.Rendering.Animation; using PushButtonState = System.Windows.Forms.VisualStyles.PushButtonState; @@ -154,11 +155,6 @@ public override void RenderControl(Graphics graphics) : flatAppearance.BorderColor; } - using (PaintEventArgs paintEventArgs = new(graphics, button.ClientRectangle)) - { - button.PaintBackground(paintEventArgs, button.ClientRectangle); - } - PopupButtonRenderContext context = new() { Bounds = button.ClientRectangle, @@ -185,6 +181,22 @@ public override void RenderControl(Graphics graphics) HighContrast = highContrast }; + using GraphicsPath? bodyPath = PopupButtonKeyCapRenderer.CreateBodyPath(context); + if (bodyPath is null) + { + using PaintEventArgs paintEventArgs = new(graphics, button.ClientRectangle); + button.PaintBackground(paintEventArgs, button.ClientRectangle); + } + else + { + ParentBackgroundRenderer.Paint( + button, + graphics, + button.ClientRectangle, + bodyPath, + button.Parent?.BackColor ?? button.BackColor); + } + Action? paintImage = null; Image? image = button.Image; diff --git a/src/System.Windows.Forms/System/Windows/Forms/Rendering/Button/PopupButtonKeyCapRenderer.cs b/src/System.Windows.Forms/System/Windows/Forms/Rendering/Button/PopupButtonKeyCapRenderer.cs index b902eb079fc..f849d43a6b4 100644 --- a/src/System.Windows.Forms/System/Windows/Forms/Rendering/Button/PopupButtonKeyCapRenderer.cs +++ b/src/System.Windows.Forms/System/Windows/Forms/Rendering/Button/PopupButtonKeyCapRenderer.cs @@ -30,6 +30,20 @@ namespace System.Windows.Forms.Rendering.Button; /// internal static class PopupButtonKeyCapRenderer { + internal static GraphicsPath? CreateBodyPath(PopupButtonRenderContext context) + { + ArgumentNullException.ThrowIfNull(context); + + Rectangle bounds = context.Bounds; + if (context.HighContrast || bounds.Width < 8 || bounds.Height < 8) + { + return null; + } + + Metrics metrics = Metrics.Create(context); + return CreateRoundedPath(metrics.KeyRect, metrics.CornerRadius); + } + /// /// Renders the key into the given . /// @@ -73,7 +87,7 @@ public static void Render(Graphics graphics, PopupButtonRenderContext context, A (Rectangle textBounds, Rectangle imageBounds) = CreateContentLayout( context, metrics.BowlRect, - applySurfaceInset: true); + applySurfaceInset: false); GraphicsState state = graphics.Save(); @@ -279,11 +293,6 @@ private static void DrawText( return; } - // The key top already moves with the press; the caption sinks a touch further, which sells the - // "finger pushes the key down" moment. - int extraSink = (int)MathF.Round(context.AnimationState.PressProgress * 0.75f * metrics.Scale); - textRect.Offset(0, extraSink); - TextFormatFlags flags = GetTextFormatFlags(context); int reliefOffset = metrics.TextReliefOffset; @@ -407,6 +416,9 @@ private static (Rectangle TextBounds, Rectangle ImageBounds) CreateContentLayout contentBounds = ApplyPadding(contentBounds, context.Padding); bool hasText = !string.IsNullOrEmpty(context.Text); bool hasImage = !context.ImageSize.IsEmpty; + ContentAlignment imageAlign = context.RightToLeft == RightToLeft.Yes + ? MirrorAlignment(context.ImageAlign) + : context.ImageAlign; if (!hasImage) { @@ -421,7 +433,7 @@ private static (Rectangle TextBounds, Rectangle ImageBounds) CreateContentLayout { return ( hasText ? contentBounds : Rectangle.Empty, - AlignInRectangle(contentBounds, imageSize, context.ImageAlign)); + AlignInRectangle(contentBounds, imageSize, imageAlign)); } TextImageRelation relation = context.RightToLeft == RightToLeft.Yes @@ -435,7 +447,7 @@ private static (Rectangle TextBounds, Rectangle ImageBounds) CreateContentLayout TextImageRelation.TextBeforeImage => CreateHorizontalLayout(imageFirst: false), TextImageRelation.ImageAboveText => CreateVerticalLayout(imageFirst: true), TextImageRelation.TextAboveImage => CreateVerticalLayout(imageFirst: false), - _ => (contentBounds, AlignInRectangle(contentBounds, imageSize, context.ImageAlign)) + _ => (contentBounds, AlignInRectangle(contentBounds, imageSize, imageAlign)) }; (Rectangle TextBounds, Rectangle ImageBounds) CreateHorizontalLayout(bool imageFirst) @@ -450,7 +462,7 @@ private static (Rectangle TextBounds, Rectangle ImageBounds) CreateContentLayout return ( textBounds, - AlignInRectangle(imageSlot, imageSize with { Width = imageWidth }, context.ImageAlign)); + AlignInRectangle(imageSlot, imageSize with { Width = imageWidth }, imageAlign)); } (Rectangle TextBounds, Rectangle ImageBounds) CreateVerticalLayout(bool imageFirst) @@ -465,7 +477,7 @@ private static (Rectangle TextBounds, Rectangle ImageBounds) CreateContentLayout return ( textBounds, - AlignInRectangle(imageSlot, imageSize with { Height = imageHeight }, context.ImageAlign)); + AlignInRectangle(imageSlot, imageSize with { Height = imageHeight }, imageAlign)); } } @@ -608,6 +620,9 @@ private static ContentAlignment MirrorAlignment(ContentAlignment alignment) /// private readonly struct Metrics { + private const float SideClearanceDip = 1f; + private const float PressTravelDip = 1.5f; + public float Scale { get; init; } public int Ambient { get; init; } public int BorderWidth { get; init; } @@ -632,19 +647,27 @@ public static Metrics Create(PopupButtonRenderContext context) float hover = context.AnimationState.HoverProgress; float press = context.AnimationState.PressProgress; - int ambient = Math.Max(1, (int)MathF.Round(2.5f * scale)); + int sideClearance = Math.Max(1, (int)MathF.Round(SideClearanceDip * scale)); + int pressTravel = Math.Max(1, (int)MathF.Round(PressTravelDip * scale)); + int ambient = sideClearance + pressTravel; int maxBorder = Math.Max(0, (Math.Min(bounds.Width, bounds.Height) / 4) - 1); int defaultBorderIncrease = context.IsDefault && context.Enabled ? Math.Max(1, (int)MathF.Round(scale)) : 0; int borderWidth = Math.Clamp(context.BorderWidth + defaultBorderIncrease, 0, maxBorder); - Rectangle keyRect = Rectangle.Inflate(bounds, -ambient, -ambient); - - // Pressing sinks the key top; the bottom edge stays put, so the cap compresses. - int pressOffset = (int)MathF.Round(press * 1.5f * scale); - keyRect.Y += pressOffset; - keyRect.Height = Math.Max(4, keyRect.Height - pressOffset); + Rectangle keyRect = new( + bounds.X + sideClearance, + bounds.Y + sideClearance, + Math.Max(1, bounds.Width - (2 * sideClearance)), + Math.Max(1, bounds.Height - sideClearance - ambient)); + + // Pressing translates the complete key top into the space released by its shortening shadow. + // Keeping the key height constant avoids moving the bowl, border, and content independently. + int pressOffset = Math.Min( + (int)MathF.Round(press * PressTravelDip * scale), + Math.Max(0, bounds.Bottom - sideClearance - keyRect.Bottom)); + keyRect.Offset(0, pressOffset); int rim = Math.Max(2, (int)MathF.Round(3f * scale)); int bowlInset = borderWidth + rim; diff --git a/src/test/integration/UIIntegrationTests/NumericUpDownTests.cs b/src/test/integration/UIIntegrationTests/NumericUpDownTests.cs index f835831c3f0..1d0fac899fa 100644 --- a/src/test/integration/UIIntegrationTests/NumericUpDownTests.cs +++ b/src/test/integration/UIIntegrationTests/NumericUpDownTests.cs @@ -27,4 +27,25 @@ await RunSingleControlTestAsync(async (form, control) => Assert.NotNull(focused); }); } + + [WinFormsFact] + public async Task NumericUpDown_ModernChrome_UsesInsetEditAndSideBySideButtonsAsync() + { + await RunSingleControlTestAsync(async (form, control) => + { + control.VisualStylesMode = VisualStylesMode.Net11; + control.AutoSize = true; + form.PerformLayout(); + + if (!control.UseSideBySideButtons) + { + return; + } + + Assert.True(control.Height >= control.LogicalToDeviceUnits(15) * 2); + Assert.Equal(control.LogicalToDeviceUnits(3), control.TextBox.Left); + Assert.Equal(control.LogicalToDeviceUnits(3), control.UpDownButtonsInternal.Top); + Assert.True(control.UpDownButtonsInternal.Bounds.Left >= control.TextBox.Bounds.Right); + }); + } } diff --git a/src/test/integration/UIIntegrationTests/VisualStylesCrossFeatureTests.cs b/src/test/integration/UIIntegrationTests/VisualStylesCrossFeatureTests.cs new file mode 100644 index 00000000000..df29d20c6e5 --- /dev/null +++ b/src/test/integration/UIIntegrationTests/VisualStylesCrossFeatureTests.cs @@ -0,0 +1,226 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Drawing; +using System.Drawing.Drawing2D; + +namespace System.Windows.Forms.UITests; + +public class VisualStylesCrossFeatureTests : ControlTestBase +{ + public VisualStylesCrossFeatureTests(ITestOutputHelper testOutputHelper) + : base(testOutputHelper) + { + } + + [WinFormsFact] + public async Task VisualStyles_InheritedControls_RenderAgainstPatternedParentAcrossModesAndDpiAsync() + { + List samples = []; + + await RunFormWithoutControlAsync( + () => + { + Form form = new() + { + AutoScaleMode = AutoScaleMode.Dpi, + RightToLeft = RightToLeft.Yes, + RightToLeftLayout = true, + Size = new Size(900, 600) + }; + + PatternedGradientPanel parent = new() + { + Dock = DockStyle.Fill, + Padding = new Padding(8), + RightToLeft = RightToLeft.Yes, + VisualStylesMode = VisualStylesMode.Classic + }; + form.Controls.Add(parent); + + TableLayoutPanel table = new() + { + AutoScroll = true, + BackColor = Color.Transparent, + ColumnCount = 3, + Dock = DockStyle.Fill, + RowCount = 11 + }; + table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 32)); + table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 34)); + table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 34)); + parent.Controls.Add(table); + + table.Controls.Add(new Label { Text = "Control / font", AutoSize = true }, 0, 0); + table.Controls.Add(new Label { Text = "AutoSize", AutoSize = true }, 1, 0); + table.Controls.Add(new Label { Text = "Fixed small", AutoSize = true }, 2, 0); + + string[] controlKinds = ["TextBox", "MaskedTextBox", "RichTextBox", "NumericUpDown", "DomainUpDown"]; + int row = 1; + foreach (float fontSize in new[] { 9f, 11f }) + { + foreach (string controlKind in controlKinds) + { + table.Controls.Add(new Label { Text = $"{controlKind} ({fontSize:0} pt)", AutoSize = true }, 0, row); + Control autoSized = CreateSampleControl(controlKind, fontSize, autoSize: true); + Control fixedSmall = CreateSampleControl(controlKind, fontSize, autoSize: false); + samples.Add(autoSized); + samples.Add(fixedSmall); + table.Controls.Add(autoSized, 1, row); + table.Controls.Add(fixedSmall, 2, row); + row++; + } + } + + return form; + }, + async form => + { + Panel parent = (Panel)form.Controls[0]; + Assert.Equal(form.DeviceDpi, parent.DeviceDpi); + Assert.All(samples, sample => Assert.Equal(RightToLeft.Yes, sample.RightToLeft)); + + foreach (Control sample in samples) + { + Assert.Equal(VisualStylesMode.Classic, sample.VisualStylesMode); + Assert.True(sample.Width > 0); + Assert.True(sample.Height > 0); + using Bitmap bitmap = new(sample.Width, sample.Height); + sample.DrawToBitmap(bitmap, new Rectangle(Point.Empty, sample.Size)); + } + + parent.VisualStylesMode = VisualStylesMode.Net11; + form.PerformLayout(); + Assert.All(samples, sample => Assert.Equal(VisualStylesMode.Net11, sample.VisualStylesMode)); + + foreach (Control sample in samples) + { + using Bitmap bitmap = new(sample.Width, sample.Height); + sample.DrawToBitmap(bitmap, new Rectangle(Point.Empty, sample.Size)); + } + + parent.VisualStylesMode = VisualStylesMode.Classic; + await Task.Yield(); + Assert.All(samples, sample => Assert.Equal(VisualStylesMode.Classic, sample.VisualStylesMode)); + }); + } + + [WinFormsFact] + public async Task VisualStyles_StandardSystemAndPopup_RenderFocusedDefaultAndPressedStatesAsync() + { + await RunFormWithoutControlAsync( + () => + { + Form form = new() { Size = new Size(500, 220) }; + FlowLayoutPanel panel = new() + { + Dock = DockStyle.Fill, + RightToLeft = RightToLeft.Yes, + FlowDirection = FlowDirection.LeftToRight + }; + form.Controls.Add(panel); + form.RightToLeft = RightToLeft.Yes; + form.RightToLeftLayout = true; + form.AutoScaleMode = AutoScaleMode.Dpi; + + Button standard = CreateButton(FlatStyle.Standard, "Standard"); + standard.NotifyDefault(true); + form.AcceptButton = standard; + panel.Controls.Add(standard); + foreach (FlatStyle style in new[] { FlatStyle.System, FlatStyle.Popup }) + { + Button button = CreateButton(style, style.ToString()); + button.NotifyDefault(true); + panel.Controls.Add(button); + } + + return form; + }, + async form => + { + FlowLayoutPanel panel = (FlowLayoutPanel)form.Controls[0]; + foreach (Button button in panel.Controls.OfType