Windows forms design mode universal solution

60 Views Asked by At

TL;DR: Is there an universal solution for the well-known design-mode problem in Windows Forms?

Windows Forms form design relies heavily on visual designer, which then generates proper initialization code (in contrast to, say, WPF, where window layout is designed declaratively). The problem is, that some of the code shouldn't run if window or control is in design mode (say, loading data from database).

There are some well-known solutions to this problem, but all works only partially:

  • Component.DesignMode - works only on top-level controls (won't work in a control placed on a control) and doesn't work at all in constructors (where actually it is needed most)
  • LicenseManager.UsageMode == LicenseUsageMode.Designtime - in turn works only in constructurs (so won't work - say - in OnPaint method
  • Checking for current process being devenv.exe - what is, let's be honest, more of a painful workaround than solid, deterministic, working method

I've been wondering, if there's a way to deterministically and repeatably verify if control or form is in debug mode?

The only solution I've come with would be to create specific configuration for design mode only, set a compilation variable and use conditional compilation:

public MyForm()
{
    InitializeComponent();
#ifndef Design
    ...
#endif
}

The problems are:

  • This needs to be switched manually
  • If you forget to switch configuration back to Debug or Release, half of the application will probably stop working. However one may solve it by stopping build quickly in Main method:

    static void Main()
    {
    #ifdef Design
        #error Exit design configuration first!
    #endif
    }
    

References:

  1. http://dotnetfacts.blogspot.com/2009/01/identifying-run-time-and-design-mode.html
0

There are 0 best solutions below