Tuesday, 3 January 2012

Windows Forms

The System.Windows.Forms namespace allows us to create Windows applications easily. The Form class is a particularly important part of that namespace because the form is the key graphical building block ofWindows applications. It provides the visual frame that holds buttons, menus, icons, and title bars together. Integrated development environments (IDEs) like Visual C# and SharpDevelop can help create graphical applications, but it is important to know how to do so manually:
using System.Windows.Forms;
public class ExampleForm : Form // inherits from System.Windows.Forms.Form
{
public static void Main()
{
ExampleForm wikibooksForm = new ExampleForm();
wikibooksForm.Text = "I Love Wikibooks";// specify title of the form
wikibooksForm.Width = 400; // width of the window in pixels
wikibooksForm.Height = 300; // height in pixels
Application.Run(wikibooksForm); // display the form
}
}
The example above creates a simple Window with the text "I Love Wikibooks" in the title bar. Custom form classes like the example above inherit from the System.Windows.Forms.Form class. Setting any of the properties Text, Width, and Height is optional. Your program will compile and run successfully if you comment these lines out, but they allow us to add extra control to our form.