views:

67

answers:

2

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

Since the beginning of Visual Studio, there has been easy way to describe the shape of a Dialog (now called a Form) in the resource file and then use a wizard to create the corresponding C++ code. I kind of remember that in MFC it was pretty much a no-brainer to create a custom dialog with all the components you want and then all the associated code.

If I have a C# app that has many forms that I want to bring to the screen based on the user's menu selections, how do I create a class associated with a windows form?

+3  A: 

If you are using the designer then it generates the C# class for you; so if have a form called UserOptionsForm, you should 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)
}
Marc Gravell
It is easier than I had thought. I am going to pop up the dialog like this: form.ShowDialog(); // returns result code (OK/cancel/etc) Once I have the dialog just as I want it, complete with an "OK" and "Cancel" button and I am able to edit code within those events, how do I use C# code to close the dialog?
xarzu
A: 

In .Net (C#, VB.Net, or whatever .Net language you're using), forms are classes, not necessarily involving resource files at all. Creating a form is as easy as inheriting the Form class:

public class MyWindow : Form
{
}

You can now bring it to the screen:

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

The window will be quite empty 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 built up using code. Now coding up forms like this by hand is tedious, so do use the WinForms Designer in Visual Studio. It will generate the code for you.

Peter Lillevold