February 23rd, 2023

Updated Modern Code Generation for WinForm’s InitializeComponent

Klaus Loeffelmann
Senior Software Engineer

When you create a WinForms Form or User Control with the WinForms Designer in Visual Studio, it does not have a special definition or file format like XML or HTML to represent the user interface. From the beginning, the only format WinForms has used is program code. A Form or User Control defined in a WinForms Visual Basic project gets saved into VB Code. In a C# project, that is C# code. That code will be placed in a dedicated Designer file, which sits behind the actual Form code file and contains the code to control the UI.

Screenshot of a WinForms Form code-behind Designer file in the Solution Explorer

When your Form or User Control needs to be opened again inside of the WinForms Designer, that code is interpreted and – based on the resulting object graph – the Form/User Control gets recreated in the Designer. That is the reason we call the process of saving a Form CodeDOM serialization. CodeDOM here refers to an object model (the Code Document Object Model) which allows the developer to define aspects of a program or part of a program by objects of certain types.

Screenshot of a WinForms Form with a Button and the respective generated code in InitializeComponent

While CodeDOM is pretty flexible, can be extended comparatively easily and supports more languages than Visual Basic or C#, generating a CodeDOM graph from an existing code file is a completely different beast. And although CodeDOM has the option to actually write a code file for particular languages through its existing Compiler implementation, the style of that resulting code is the same it has been from the beginning of .NET Framework, which is in many cases no longer up to current coding standards.

In WinForms, when you design a Form, everything which is relevant is generated in one method per Form or User Control. That method (amongst a bit of infrastructure and initialization code in addition) is called InitializeComponent.

This method is called by a Form’s constructor unconditionally. In the C# case that’s pretty obvious, where a new Form which you add to your project, always has that constructor and the required call:

    public partial class Form1 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
    }

In Visual Basic, if you don’t add a constructor Sub New explicitly, the Visual Basic compiler inserts the call to InitializeComponent automatically in the background. If you however add a constructor to the code file, the editor also inserts the call to InitializeComponent in the VB code:

Public Class Form1

    Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub
End Class

Note that in Visual Basic, the Inherits statement, which lets your new Form class inherit from the System.Windows.Forms.Form base class, in contrast to C# is only part of the Designer code behind file. In VB it’s also sufficient for a partial class only to state the Partial keyword in one of the partial class’ code files. That is the reason why a Visual Basic WinForms Form code file does not contain anything but the Form’s class definition by default.

Up to recently, the WinForms Designer used the CodeModel Interface to interpret source code of the different programming language to build the required internal CodeDOM graph for the Designer to hold a Form’s or a User Control’s definition. But we changed that.

Enter Roslyn

WinForms introduced with Visual Studio 2022 version 17.5 a modernized way to read and generate the code for InitializeComponent for the WinForms Out-of-Process Designer. It does so by using the APIs of the .NET Compiler Platform – better know as the Roslyn SDK – for all related tasks. The Roslyn Compiler is a set of open-source compilers and code analysis APIs for .NET languages. It allows developers to write, analyze, and manipulate code in C# and Visual Basic .NET using modern language features. It also provides a rich set of diagnostic and code refactorings to improve code quality and developer productivity. It is the gold standard and the current best practice for code generation in C# and VB. And, since it’s the same tooling that is used for compilation and build purposes inside Visual Studio for any C# or Visual Basic project its code generation result is completely in-line with current coding standards.

Also, since the Roslyn compiler provides certain APIs to not know only about the correct syntax of a particular statement, command or method, but also about the semantics of a code block already at WinForms design time, the WinForms designer can point out potential problems with the code inside of InitializeComponent far earlier and more precisely than before. So, it not only knows when you’ve spelled ‘Buttne’ wrong – it would also know that a variable with a typo defined inside of InitializeComponent would be an unknown symbol, and be able to point that out.

But there is a series of additional benefits:

  • Previously, the CodeModel based building up of the CodeDOM could only run on the UI Thread. That was not only a blocking operation, it couldn’t utilize the full potential of a modern, multi-core processor. Using the Roslyn compiler, we will be able to optimize the building process over time by using parallelization.
  • The old system didn’t have an easy way to interpret more recently introduced language features. Using Roslyn, we will have the option to introduce language features like NameOf to generate more robust code, especially for data binding purposes. In addition it opens up the path to more complex code generation inside of InitializeComponent in the future, which will help to optimize and equalize code generation for HighDPI scenarios generated on machines with different HighDPI settings.
  • The Roslyn compiler honors many aspects of .editorconfig configurations, so the code generated in InitializeComponent is close to what you and your team are enforcing as your coding standards by custom .editorconfig definitions.

That all said, there are a couple of coding elements which are fundamentally different than before. The omission of this in C# or Me in Visual Basic is one of such an example. The following screenshot shows the difference in the code generation with Roslyn for a Button in InitializeComponent:

Screenshot of a diff of InitializeComponent with the classic and the new Roslyn-based code generation

If you’re interested in a more technical background about moving the code generation in the WinForms designer to Roslyn or how to configure the InitializeComponent code generation with .editorconfig, take a look at this technical article in the WinForms repo who points out all those things in greater detail.

Feedback about the subject matter is really important to us, so please let us know your thoughts or ideas you might have around WinForms code generations in the comments. If you have suggestions around the WinForms Designer or think you found a bug, feel free to file new issues in the WinForms Github repo.

Happy designing and coding!

Author

Klaus Loeffelmann
Senior Software Engineer

27 comments

Discussion is closed. Login to edit/delete existing comments.

  • Laurent Bourgeois · Edited

    Winforms is certainly not dead. I’m still a big fan of it. It is possible to modernize the way you develop by using only code to build your UI.
    Have a look at this very inspiring project on github :
    WinFormMarkup
    Thanks to this way of doing things, I now have minimal code to represent a form, and that contains only data-bounds controls.

  • Rich Howard

    Looks like 17.5 Winforms Designer now auto formats not only designer code but my attached code as well. This is a total stop for me. How can we turn off auto formatting of all but designer files?

    • Klaus LoeffelmannMicrosoft employee Author

      The WinForms Designer is only supposed to touch and pretty-list/format code inside of the code behind (Designer) file. We have hit a couple of corner cases (mostly in the VB space), where it does either more or less of which it's supposed to do, and those cases we are going to service for 17.5. I want to understand your case better. Could get in touch (klaus dot loeffelmann ät microsoft dot com) or open an...

      Read more
  • Will Woo · Edited

    "WinForms introduced with Visual Studio 2022 version 17.5 a modernized way to read and generate the code for InitializeComponent for the WinForms Out-of-Process Designer. It does so by using the APIs of the .NET Compiler Platform – better know as the Roslyn SDK – for all related tasks."

    Perhaps this explains the frequent failure of 7.5 to render the Design View ... with odd visual results and/or no error messages, or strange error messages ?

    I have...

    Read more
    • Klaus LoeffelmannMicrosoft employee Author

      I have been working in C# WinForms and VS from 2002, but, I must be on another planet where what the author refers to as “code” in the Designer.cs files is as fat/thin as XML/XAML, or, any other descriptive “recipe” for serializing/rendering the attributes, properties, events, etc., of an interface … Just as event binding can be done in XAML, it is done in Designer files.

      By all means: The work, we are doing...

      Read more
    • Maximilien Noal

      Just use AvaloniaUI, instead.

      It has none of those issues.

  • Daite Dve

    Sorry, didn't catch all "greatness" of improvements. I see you simply get rid of unnecessary "this." and at last start using namespaces instead of full naming. IS IT ALL?!?! What about most ugliest idea - to keep design(!!!) of form in CODE?? It's totally stupid even for 200* years!
    Design is declaration - like XML, JSON, whatever. Why MS still keeps old shity code for WinForms? You had to move at least to XML! (like...

    Read more
  • Alexander Wurzinger

    Just a litle TipEx I noticed, the C# Code of Has a Class with then Name ‘Form1’ and the Konstructor is call ‘Form2’.
    This should also be Form1

  • Michael Winsor · Edited

    It's quite nice to see more work being done on the WinForms front.

    My only complaint is how high DPI is handled when designing. Currently, I have to to make Visual Studio DPI unaware in order to do any edits to my forms/controls. The 'switch to 100%' doesn't work well for me, so in the end I have to disable DPI awareness. It would be nice (and easier on my old, tired eyes) if...

    Read more
  • Richard Moss

    One thing which I don’t think has been addressed (and so apologies if I missed it) is to what flavour of WinForms this supports – is it global, irrespective of .NET Framework or .Core, or is it tied only to .NET 5+?

    The mention of the out of process designer hints that this is 5+ only.

    Thanks;
    Richard Moss

    • Klaus LoeffelmannMicrosoft employee Author

      We could address this also in the Out-Of-Proc Designer for .NET Framework, which we are working on to address issues in 64-Bit Visual Studio 2022 and really old WinForms apps, which still rely on 32-Bit-only (often) COM based components. But we figure that it would too much of a mismatch between the style of generated code with the in-proc and the out-of-proc Designer, so this feature probably only makes sense for WinForms apps going forward...

      Read more
      • Paolo Fornari

        I really would like to see it in .NET framework also, especially binding code generated with the use of NameOf.
        We want to upgrade to .NET 6,7,8+ but we need (and waiting) the new OOP designer to reach to parity of functionality of .NET framework one.

  • Max Mustermueller

    Meanwhile WPF team: zzzZZZZzzzz

    • Hughes, Danial

      Sigh…whilst i love to see the improvements to WinForms, i would also love to see a similar investment in WPF. I keep saying it but why would anyone embrace new Microsoft technology (i.e. MAUI) when Microsoft have demonstrated as soon as something new and shiny comes along they will drop you.

      • Tanveer Badar

        /me name drops silverlight and WCF.

    • Paulo Pinto

      It isn’t that bad, at least it has a designer, Blend support, DirectX support exposed to .NET and XAML, form validation, and not 3000 bugs and counting, as WinUI.

  • gf s

    could be leave a way to call custom Method from InitializeComponent,between SuspendLayout and ResumeLayout.
    because some winform control not stable.so let use write code to design the UI is very important !
    Designers don't have the flexibility to handle everything. Usually the code is more controllable.

    WinForm would be great if I implemented my request, because it would be possible to write the UI code while watching a preview in the designer of the code...

    Read more
    • Klaus LoeffelmannMicrosoft employee Author

      I am not entirely sure what you mean, or to what end you want to do that, but for a more controlled initialization of components or controls, you can use ISupportInitialize. That's used for components with depending properties, where the order in which the writing of properties takes place, does matter. Basically, your control will be informed when the initialization starts and when it ends. In the meantime, for the properties in question, you are...

      Read more
  • Edison Henrique Andreassy

    Thanks for this update. It’s really nice see WinForms evolving! I would like to know where should I report problems for issues on this matter, for example, I’m getting wrong serialization (and compiler error) when I select a project resource instead local resource (in VB). I also have intereset in using my skills to try contribuite fixing this kind of bug.

    • Merrie McGawMicrosoft employee

      To add to the comment Klaus made – sometimes we get a little bit more logging and diagnostic information if you file a feedback ticket through Visual Studio. That said, we’re more than happy to work with you either way you choose to communicate – we are just happy to have the feedback so we can address the most pressing problems faster 🙂.

      ~Merrie McGaw, WinForms engineering team lead.