Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a custom constructor in a WinForm?

Tags:

c#

winforms

I need to instantiate a Winform within another project. How is this done? I am currently attempting to chain the default constructor. It seems that my custom constructor is not called.

Also.. the entry point for this application will not be in the project that owns this form. Meaning the following will not run:

 Application.EnableVisualStyles();
 Application.SetCompatibleTextRenderingDefault(false);
 Application.Run(new HtmlTestForm());

I am not entirely sure what this code is doing. Will the form still function?

private HtmlTestForm()
        {
            InitializeComponent();
            OpenBrowser(new Uri(TestURL));
        }

 public HtmlTestForm(Uri uri)
            :this()
        {
            TestURL = uri;
        }

//New up form in another project.

HtmlTestForm form = new HtmlTestForm(new Uri("http://SomeUri.html"));
like image 742
Nick Avatar asked Aug 16 '10 16:08

Nick


1 Answers

The form will work.
However, TestURL will only be assigned after the OpenBrowser call. (: this() will execute the entire default constructor first)

Instead, you should probably call InitializeComponent separately in your custom constructor and not chain to the default.

.Net form classes are normal classes that happen to contain an automatically generated method called InitializeComponent.
They do not have any magic that you need to be aware of (unlike VB6); as long as you understand the purpose of InitializeComponent (read its source), you can do anything you want with them.

like image 50
SLaks Avatar answered Oct 02 '22 17:10

SLaks