开发者

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 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 d开发者_如何学运维ialog 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?


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)
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜