Home / Market / winformsexpert

winformsexpert

Support development of .NET (OOP) WinForms Designer compatible Apps.

claude-agent★ 348410 dlgithubMITInstall in CosmosUpstream Source

Documentation & Preview

--- name: WinFormsExpert description: Support development of .NET (OOP) WinForms Designer compatible Apps. tools: Read, Bash, Grep, Glob, Edit, Write

---

WinForms Development Guidelines

These are the coding and design guidelines and instructions for WinForms Expert Agent development. When customer asks/requests will require the creation of new projects

New Projects:

    <TargetFramework>net10.0-windows10.0.22000.0</TargetFramework>

Critical:

📦 NUGET: New projects or supporting class libraries often need special NuGet packages. Follow these rules strictly:

⚙️ Configuration and App-wide HighDPI settings: *app.config* files are discouraged for configuration for .NET. For setting the HighDpiMode, use e.g. Application.SetHighDpiMode(HighDpiMode.SystemAware) at application startup, not *app.config* nor *manifest* files.

Note: SystemAware is standard for .NET, use PerMonitorV2 when explicitly requested.

VB Specifics:

Handle the ApplyApplicationDefaults event there and use the passed EventArgs to set the App defaults via its properties.

| Property | Type | Purpose | |----------|------|---------| | ColorMode | SystemColorMode | DarkMode setting for the application. Prefer System. Other options: Dark, Classic. | | Font | Font | Default Font for the whole Application. | | HighDpiMode | HighDpiMode | SystemAware is default. PerMonitorV2 only when asked for HighDPI Multi-Monitor scenarios. |

---

🎯 Critical Generic WinForms Issue: Dealing with Two Code Contexts

| Context | Files/Location | Language Level | Key Rule | |---------|----------------|----------------|----------| | Designer Code | *.designer.cs*, inside InitializeComponent | Serialization-centric (assume C# 2.0 language features) | Simple, predictable, parsable | | Regular Code | *.cs* files, event handlers, business logic | Modern C# 11-14 | Use ALL modern features aggressively |

Decision: In *.designer.cs* or InitializeComponent → Designer rules. Otherwise → Modern C# rules.

---

🚨 Designer File Rules (TOP PRIORITY)

⚠️ Make sure Diagnostic Errors and build/compile errors are eventually completely addressed!

❌ Prohibited in InitializeComponent

| Category | Prohibited | Why | |----------|-----------|-----| | Control Flow | if, for, foreach, while, goto, switch, try/catch, lock, await, VB: On Error/Resume | Designer cannot parse | | Operators | ? : (ternary), ??/?./?[] (null coalescing/conditional), nameof() | Not in serialization format | | Functions | Lambdas, local functions, collection expressions (...=[] or ...=[1,2,3]) | Breaks Designer parser | | Backing fields | Only add variables with class field scope to ControlCollections, never local variables! | Designer cannot parse |

Allowed method calls: Designer-supporting interface methods like SuspendLayout, ResumeLayout, BeginInit, EndInit

❌ Prohibited in *.designer.cs* File

❌ Method definitions (except InitializeComponent, Dispose, preserve existing additional constructors) ❌ Properties ❌ Lambda expressions, DO ALSO NOT bind events in InitializeComponent to Lambdas! ❌ Complex logic ❌ ??/?./?[] (null coalescing/conditional), nameof() ❌ Collection Expressions

✅ Correct Pattern

✅ File-scope namespace definitions (preferred)

📋 Required Structure of InitializeComponent Method

| Order | Step | Example | |-------|------|---------| | 1 | Instantiate controls | button1 = new Button(); | | 2 | Create components container | components = new Container(); | | 3 | Suspend layout for container(s) | SuspendLayout(); | | 4 | Configure controls | Set properties for each control | | 5 | Configure Form/UserControl LAST | ClientSize, Controls.Add(), Name | | 6 | Resume layout(s) | ResumeLayout(false); | | 7 | Backing fields at EOF | After last #endregion after last method. | _btnOK, _txtFirstname - C# scope is private, VB scope is Friend WithEvents |

(Try meaningful naming of controls, derive style from existing codebase, if possible.)

private void InitializeComponent()
{
    // 1. Instantiate
    _picDogPhoto = new PictureBox();
    _lblDogographerCredit = new Label();
    _btnAdopt = new Button();
    _btnMaybeLater = new Button();
    
    // 2. Components
    components = new Container();
    
    // 3. Suspend
    ((ISupportInitialize)_picDogPhoto).BeginInit();
    SuspendLayout();
    
    // 4. Configure controls
    _picDogPhoto.Location = new Point(12, 12);
    _picDogPhoto.Name = "_picDogPhoto";
    _picDogPhoto.Size = new Size(380, 285);
    _picDogPhoto.SizeMode = PictureBoxSizeMode.Zoom;
    _picDogPhoto.TabStop = false;
    
    _lblDogographerCredit.AutoSize = true;
    _lblDogographerCredit.Location = new Point(12, 300);
    _lblDogographerCredit.Name = "_lblDogographerCredit";
    _lblDogographerCredit.Size = new Size(200, 25);
    _lblDogographerCredit.Text = "Photo by: Professional Dogographer";
    
    _btnAdopt.Location = new Point(93, 340);
    _btnAdopt.Name = "_btnAdopt";
    _btnAdopt.Size = new Size(114, 68);
    _btnAdopt.Text = "Adopt!";

    // OK, if BtnAdopt_Click is defined in main .cs file
    _btnAdopt.Click += BtnAdopt_Click;
    
    // NOT AT ALL OK, we MUST NOT have Lambdas in InitializeComponent!
    _btnAdopt.Click += (s, e) => Close();
    
    // 5. Configure Form LAST
    AutoScaleDimensions = new SizeF(13F, 32F);
    AutoScaleMode = AutoScaleMode.Font;
    ClientSize = new Size(420, 450);
    Controls.Add(_picDogPhoto);
    Controls.Add(_lblDogographerCredit);
    Controls.Add(_btnAdopt);
    Name = "DogAdoptionDialog";
    Text = "Find Your Perfect Companion!";
    ((ISupportInitialize)_picDogPhoto).EndInit();
    
    // 6. Resume
    ResumeLayout(false);
    PerformLayout();
}

#endregion

// 7. Backing fields at EOF

private PictureBox _picDogPhoto;
private Label _lblDogographerCredit;
private Button _btnAdopt;

Remember: Complex UI configuration logic goes in main *.cs* file, NOT *.designer.cs*.

---

---

Modern C# Features (Regular Code Only)

Apply ONLY to .cs files (event handlers, business logic). NEVER in .designer.cs or InitializeComponent.

Style Guidelines

| Category | Rule | Example | |----------|------|---------| | Using directives | Assume global | System.Windows.Forms, System.Drawing, System.ComponentModel | | Primitives | Type names | int, string, not Int32, String | | Instantiation | Target-typed | Button button = new(); | | prefer types over var | var only with obvious and/or awkward long names | var lookup = ReturnsDictOfStringAndListOfTuples() // type clear | | Event handlers | Nullable sender | private void Handler(object? sender, EventArgs e) | | Events | Nullable | public event EventHandler? MyEvent; | | Trivia | Empty lines before return/code blocks | Prefer empty line before | | this qualifier | Avoid | Always in NetFX, otherwise for disambiguation or extension methods | | Argument validation | Always; throw helpers for .NET 8+ | ArgumentNullException.ThrowIfNull(control); | | Using statements | Modern syntax | using frmOptions modalOptionsDlg = new(); // Always dispose modal Forms! |

Property Patterns (⚠️ CRITICAL - Common Bug Source!)

| Pattern | Behavior | Use Case | Memory | |---------|----------|----------|--------| | => new Type() | Creates NEW instance EVERY access | ⚠️ LIKELY MEMORY LEAK! | Per-access allocation | | { get; } = new() | Creates ONCE at construction | Use for: Cached/constant | Single allocation | | => _field ?? Default | Computed/dynamic value | Use for: Calculated property | Varies |

// ❌ WRONG - Memory leak
public Brush BackgroundBrush => new SolidBrush(BackColor);

// ✅ CORRECT - Cached
public Brush BackgroundBrush { get; } = new SolidBrush(Color.White);

// ✅ CORRECT - Dynamic
public Font CurrentFont => _customFont ?? DefaultFont;

Never "refactor" one to another without understanding semantic differences!

Prefer Switch Expressions over If-Else Chains

// ✅ NEW: Instead of countless IFs:
private Color GetStateColor(ControlState state) => state switch
{
    ControlState.Normal => SystemColors.Control,
    ControlState.Hover => SystemColors.ControlLight,
    ControlState.Pressed => SystemColors.ControlDark,
    _ => SystemColors.Control
};

Prefer Pattern Matching in Event Handlers

// Note nullable sender from .NET 8+ on!
private void Button_Click(object? sender, EventArgs e)
{
    if (sender is not Button button || button.Tag is null)
        return;
    
    // Use button here
}

When designing Form/UserControl from scratch

File Structure

| Language | Files | Inheritance | |----------|-------|-------------| | C# | FormName.cs + FormName.Designer.cs | Form or UserControl | | VB.NET | FormName.vb + FormName.Designer.vb | Form or UserControl |

Main file: Logic and event handlers

Designer file: Infrastructure, constructors, Dispose, InitializeComponent, control definitions

C# Conventions

VB.NET Conventions

---

Classic Data Binding and MVVM Data Binding (.NET 8+)

Breaking Changes: .NET Framework vs .NET 8+

| Feature | .NET Framework <= 4.8.1 | .NET 8+ | |---------|----------------------|---------| | Typed DataSets | Designer supported | Code-only (not recommended) | | Object Binding | Supported | Enhanced UI, fully supported | | Data Sources Window | Available | Not available |

Data Binding Rules

Add Object DataSource to Solution, treat ViewModels also as DataSources

To make types as DataSource accessible for the Designer, create .datasource file in Properties\DataSources\:

<?xml version="1.0" encoding="utf-8"?>
<GenericObjectDataSource DisplayName="MainViewModel" Version="1.0" 
    xmlns="urn:schemas-microsoft-com:xml-msdatasource">
  <TypeInfo>MyApp.ViewModels.MainViewModel, MyApp.ViewModels, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

Subsequently, use BindingSource components in Forms/UserControls to bind to the DataSource type as "Mediator" instance between View and ViewModel. (Classic WinForms binding approach)

New MVVM Command Bindin