How do I create a class associated with a Windows Form in C #?

Now that C ++ development has become second nature to me, do I need to start from scratch with C #?

From the beginning, Visual Studio had an easy way to describe a dialog box form (now called a form) in a resource file, and then use a wizard to generate the appropriate C ++ code. I remember that in MFC it was rather difficult to create a custom dialog with all the necessary components and then all the associated code.

If I have a C # application that has many forms that I want to display on the screen, depending on a custom menu selection, how do I create a class associated with the window form?

+2


a source to share


2 answers


If you use the constructor, it generates a C # class for you; so if you have a form called UserOptionsForm

you just need to do something like:

new UserOptionsForm().Show();

      



or for a modal popup:

using(UserOptionsForm form = new UserOptionsForm()) {
    form.ShowDialog(); // returns result code (OK/cancel/etc)
}

      

+3


a source


In .Net (C #, VB.Net, or any other .Net language), forms are classes, not necessarily associated with resource files. Creating a form is as easy as inheriting from the Form class:

public class MyWindow : Form
{
}

      

Now you can display it:

using (var myWindow = new MyWindow())
{
    myWindow.Show();
}

      



The window will be pretty blank until you add some controls to it:

public class MyWindow : Form
{
    public MyWindow()
    {
         var button = new Button();
         button.Text = "Click me";
         Controls.Add(button);
    }
}

      

As you can see, in WinForms, forms and controls are all created using code. Now coding forms like this by hand is tedious, so use the WinForms Designer in Visual Studio. It will generate the code for you.

0


a source







All Articles