0

Is there any way I can execute custom code in a Winforms Form when it is opened in the Designer?

As far as I can see, only the InitializeComponent Method is called by the Designer. Neither the Form's constructor nor any event (e.g. Loaded) are invoked.

Of course I could add my code to InitializeComponent. But since this method is re-generated by the Designer all the time this is not a good idea...

Boris
  • 8,551
  • 25
  • 67
  • 120
  • I remember there was a concept called DesignTime that was intended to do this – isaeid Mar 13 '19 at 10:25
  • 1
    I'm afraid I don't get what you're aiming at. Can you elaborate? – Boris Mar 13 '19 at 10:36
  • In form onload method i can add if (this.DesignMode) and execute some codes only in design time. – isaeid Mar 13 '19 at 11:08
  • But the OnLoad event is never raised on a WinForms form during design time? – Boris Mar 13 '19 at 11:17
  • Checkout these posts: https://stackoverflow.com/questions/4346361/winform-custom-control-designmode-doesnt-return-true-whereas-in-design-mode https://stackoverflow.com/questions/34664/designmode-with-nested-controls/708594#708594 https://www.codeproject.com/Tips/447319/Resolve-DesignMode-for-a-User-Control – gunnerone Mar 13 '19 at 14:10
  • All these links only refer to detecting if DesignMode is true/false. That's not what I'm looking for. – Boris Mar 14 '19 at 09:09
  • Yes you can run code in design mode. Whatever you put in constructor of the base form if your form, will run when your form opens in designer. To learn more about it, take a look at this post: [Show controls added programatically in WinForms app in Design view?](https://stackoverflow.com/a/33535154/3110834) or this one: [Can't view designer when coding a form in C#](https://stackoverflow.com/a/32299687/3110834). – Reza Aghaei Apr 26 '19 at 21:11
  • I have this exact need and I need it because I want to add a control in code, not drop it in the design editor. Why? Because I am creating forms that are just containers for my WPF controls and it's faster to paste a code than dropping it in the designer and setting dock or whatever. I want to edit those forms as little as possible. I don't want to even have those forms but I need them to be able to set the default form size in the designer based on how the control looks, otherwise I would just generate those forms in the code. – Hrvoje Batrnek Nov 20 '19 at 22:25
  • I've tried removing InitializeComponent from the constructor and that did not break the designer, which means that InitializeComponent is called directly from the designer and InitializeComponent in the constructor is called in runtime. If you rename the InitializeComponent in the designer it will create a new InitializeComponent method. – Hrvoje Batrnek Nov 20 '19 at 22:35

0 Answers0