WinFormsExpert
Support development of .NET (OOP) WinForms Designer compatible Apps.
$ npx claude-code-templates@latest --agent="expert-advisors/WinFormsExpert" --yesRequires Claude Code. The command adds this agent to your project's .claudedirectory β nothing runs on ToolZip's servers.
What's inside this agent
Component source (preview)
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:- Prefer .NET 10+. Note: MVVM Binding requires .NET 8+.
- Prefer
Application.SetColorMode(SystemColorMode.System);inProgram.csat application startup for DarkMode support (.NET 9+). - Make Windows API projection available by default. Assume 10.0.22000.0 as minimum Windows version requirement.
<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:
- Prefer well-known, stable, and widely adopted NuGet packages - compatible with the project's TFM.
[2.,)
βοΈ 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.
- In VB, do NOT create a Program.vb - rather use the VB App Framework.
- For the specific settings, make sure the VB code file ApplicationEvents.vb is available.
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 |
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 |
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 |
Dispose, InitializeComponent, control definitions
C# Conventions
- File-scoped namespaces
- Assume global using directives
- NRTs OK in main Form/UserControl file; forbidden in code-behind
.designer.cs - Event _handlers_:
object? sender - Events: nullable (
EventHandler?)
VB.NET Conventions
- Use Application Framework. There is no
Program.vb. - Forms/UserControls: No constructor by default (compiler generates with
InitializeComponent()call) - If constructor needed, include
InitializeComponent()call - CRITICAL:
Friend WithEvents controlName as ControlTypefor control backing fields. - Strongly prefer event handlers
Subs withHandlesclause in main code overAddHandlerin fileInitializeComponent
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
- Object DataSources:
INotifyPropertyChanged,BindingList<T>required, preferObservableObjectfrom MVVM CommunityToolkit. ObservableCollection<T>: RequiresBindingList<T>a dedicated adapter, that merges both change notifications approaches. Create, if not existing.- One-way-to-source: Unsupported in WinForms DataBinding (workaround: additional dedicated VM property with NO-OP property setter).
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 Binding APIs in .NET 8+
| API | Description | Cascading |
|---|---|---|
Control.DataContext | Ambient property for MVVM |
Preview truncated. View the full source on GitHub β
Related Claude Code Agents
Architect Review
Use this agent to review code for architectural consistency and patterns. Specializes in SOLID principles, proper layering, and maintainability. Examples: <example>Context: A developer has submitted a pull request with significant structural changes. user: 'Please review the architecture of this new feature.' assistant: 'I will use the architect-reviewer agent to ensure the changes align with our existing architecture.' <commentary>Architectural reviews are critical for maintaining a healthy codebase, so the architect-reviewer is the right choice.</commentary></example> <example>Context: A new service is being added to the system. user: 'Can you check if this new service is designed correctly?' assistant: 'I'll use the architect-reviewer to analyze the service boundaries and dependencies.' <commentary>The architect-reviewer can validate the design of new services against established patterns.</commentary></example>
Documentation Expert
Use this agent to create, improve, and maintain project documentation. Specializes in technical writing, documentation standards, and generating documentation from code. Examples: <example>Context: A user wants to add documentation to a new feature. user: 'Please help me document this new API endpoint.' assistant: 'I will use the documentation-expert to generate clear and concise documentation for your API.' <commentary>The documentation-expert is the right choice for creating high-quality technical documentation.</commentary></example> <example>Context: The project's documentation is outdated. user: 'Can you help me update our README file?' assistant: 'I'll use the documentation-expert to review and update the README with the latest information.' <commentary>The documentation-expert can help improve existing documentation.</commentary></example>
Agent Expert
|-
Dependency Manager
Use this agent to manage project dependencies. Specializes in dependency analysis, vulnerability scanning, and license compliance. Examples: <example>Context: A user wants to update all project dependencies. user: 'Please update all the dependencies in this project.' assistant: 'I will use the dependency-manager agent to safely update all dependencies and check for vulnerabilities.' <commentary>The dependency-manager is the right tool for dependency updates and analysis.</commentary></example> <example>Context: A user wants to check for security vulnerabilities in the dependencies. user: 'Are there any known vulnerabilities in our dependencies?' assistant: 'I'll use the dependency-manager to scan for vulnerabilities and suggest patches.' <commentary>The dependency-manager can scan for vulnerabilities and help with remediation.</commentary></example>
Multi Agent Coordinator
"Use when coordinating multiple concurrent agents that need to communicate, share state, synchronize work, and handle distributed failures across a system. Specifically:\\n\\n<example>\\nContext: A data pipeline has 8 specialized agents running in parallelβdata-ingestion, validation, transformation, enrichment, quality-check, storage, monitoring, and error-handling agents. They need to coordinate state changes, pass data between stages, and respond to failures anywhere in the pipeline.\\nuser: \"We have 8 agents processing data through different stages. Some need to wait for others to finish, they need to exchange data, and if one fails, others need to know about it. Can you coordinate all of this?\"\\nassistant: \"I'll set up coordination across your 8 agents by: establishing clear communication channels between dependent agents, implementing message passing for data exchange, creating dependency graphs to control execution order, setting up distributed failure detection across all agents, implementing compensation logic so if the quality-check agent fails, the transformation agent can adjust accordingly, and monitoring the entire pipeline to detect bottlenecks or cascade failures.\"\\n<commentary>\\nInvoke multi-agent-coordinator when you have multiple agents that need to work together in a tightly coupled way with shared state, synchronization points, and distributed failure handling. This is distinct from agent-organizer (which selects and assembles teams) and workflow-orchestrator (which models business processes). Use coordinator for real-time inter-agent communication.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: Running a distributed search system where a query-distributor agent sends requests to 5 parallel search-engine agents, which send results to a result-aggregator agent. The system needs to handle timeouts, partial failures, and dynamic load balancing.\\nuser: \"We're building a meta-search system where one coordinator sends queries to 5 parallel search engines, and they all need to send results to an aggregator. If some are slow, we need to handle that gracefully. How do we coordinate this?\"\\nassistant: \"I'll design the coordination using scatter-gather pattern: the query-distributor sends requests to all 5 search-engine agents in parallel, I'll implement timeout handling so slow responders don't block the aggregator, set up circuit breakers to prevent cascading failures if a search engine is down, implement partial result collection so the aggregator can combine whatever results come back within the timeout window, and add fallback logic to redistribute work if an agent fails.\"\\n<commentary>\\nUse multi-agent-coordinator for real-time synchronization of multiple agents processing in parallel, especially when dealing with timeouts, partial failures, and dynamic load balancing. This is ideal for scatter-gather patterns and real-time distributed systems.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: A microservices system has agents for user-service, order-service, inventory-service, and payment-service. They operate semi-independently but occasionally need to coordinate complex transactions like order placement that spans multiple agents with rollback requirements.\\nuser: \"Our services run independently, but when a customer places an order, we need user-service to validate the user, inventory-service to reserve stock, and payment-service to charge the card. If any step fails, all need to rollback. Can you coordinate this?\"\\nassistant: \"I'll implement coordination using a saga pattern: set up checkpoints where agents can commit or rollback state, define compensation logic for each agent (if payment fails, unreserve inventory and clear the user order), implement distributed transaction semantics so all agents reach a consistent state even under failures, establish communication channels for agents to signal state changes to each other, and add monitoring to detect and recover from partial failures.\"\\n<commentary>\\nInvoke multi-agent-coordinator when agents must maintain transactional consistency across multiple semi-independent services, requiring compensation logic and distributed commit semantics. This handles complex distributed transactions with rollback requirements.\\n</commentary>\\n</example>"
Critical Thinking
Challenge assumptions and encourage critical thinking to ensure the best possible solution and outcomes.
Catalog data and component content are sourced from the open-source davila7/claude-code-templates project (MIT license). ToolZip curates the listing and writes original descriptions; every component links back to its original source. Claude Code is a product of Anthropic. ToolZip is an independent catalog and is not affiliated with or endorsed by Anthropic.