Windows Programming using C#


This article has been excerpted from book "The Complete Visual C# Programmer's Guide from the Authors of C# Corner".

In this article, you will learn the basics of the Windows Forms platform and how to write Windows applications using Windows forms and controls. The space allocated to this article prevents an exploration of every control in the System.Windows.Forms namespace, but the following key topics are discussed and should provide the reader an ample grounding with which to tackle any orphaned controls:

  • Windows Forms and the advantages of using forms
  • Developing Windows applications using Windows Forms
  • The basics of the System.Windows.Forms namespace and its classes such as Form, Control, and other control classes
  • Working with menus, toolbars, ToolTips, and status bars
  • Working with dialog boxes
  • Working with common dialog classes

Windows Forms

Windows Forms is a framework located in the System.Windows.Forms.dll assembly for building Windows applications in .NET based on a graphical user interface (GUI). Any language that supports the common language runtime (CLR) can use Windows Forms.

Why Windows Forms?

If you have programmed in Visual Basic (VB), you are probably familiar with forms. In VB, all windows are forms. Controls are placed on forms to develop GUI applications. Visual C++ developers will more likely be familiar with windows and dialogs rather than forms (CWnd and CDialog in Microsoft Foundation Classes [MFC]).

The Microsoft .NET Framework is designed to remedy this "forms versus windows" situation. All windows are forms, including dialog boxes. From all of this synergy, Microsoft coined the term Windows form. Now developers using any .NET-supported language have access to the same windowing classes, whether they work with C#, VB, C++, or any other .NET-compliant language. This language independence has been extended to support many more languages, including COBOL.

In addition to the preceding, the main benefits of Windows Forms are its ease of use, the standardization of the control hierarchy, and that it allows for rapid application development (RAD). Changing the colors and fonts of controls using MFC or Win32 can be a real headache. The .NET Framework has taken care of most such problems and inconveniences.

In addition, Windows Forms applications provide the following:
  • Simple and flexible property support, modeled after
  • Common control support, including support for font and color dialogs
  • Support for Web Services
  • Data-aware controls using ADO.NET
  • ActiveX support
  • GDI+ (Graphical Device Interface +), a better and richer graphics library, which supports alpha blending, texture brushes, advanced transformations, and rich text
  • Metadata support

Writing Your First Windows Application

Most readers of this book are developers desiring to master C# in a Visual Studio .NET (VS.NET) environment, but VS.NET is not a mandatory tool. A Windows Forms application, indeed all applications, may be developed without using Visual Studio's integrated development environment (IDE). Simply use any text editor to write your code and save the file with a .cs extension.

Our first Windows application is a simple one that creates a window. To create a Windows-based application, you derive a class from System.Windows.Forms.Form and call the default constructor, as illustrated in Listing 9.1. The Form class acts as a container for other controls.

Listing 9.1 First Console Windows Application


using
System;
using
System.Windows.Forms;

// Derive your class from the System.Windows.Forms.Form class

public
class WinForm : Form
{
    public WinForm()
    { }

    static void Main(string[] args)
    {
       
// Create a Form object
        WinForm myFrm = new WinForm();

       
// Set the window title
        myFrm.Text = "My First Windows Application";
       
// Pass form object
        Application.Run(myFrm);
    }
}


The window's title is set by the form's Text property. The static method Application.Run creates a standard message loop on the current thread. The program, as Figure 9.1 illustrates, creates an empty form with the title "My First Windows Application" in the caption bar.

figure-9.1.gif

Figure 9.1: First Windows Application

In the Listing1-9App project you will find a file, compile.bat, that creates a Windows application, WinApp1.exe, from the following command line:

csc /target:exe /out:WinApp1.exe /reference:System.dll /reference:System.Windows.Forms.dll class1.cs

As the command line now stands, a console window will appear prior to the GUI window. The reason lies in the "/target:" compiler option, which specifies a console application with the exe string. To display only the GUI window, change the option from exe to winexe. Also be aware that the /target: option can be abbreviated to /t:, as can the /reference option to /r:. To change the name of the executable program, simply change the name linked to the /out: compiler option.

The code in Listing 9.2 adds a button and a text box to the form and creates an event handler for the button. When a user clicks the button, an event is triggered that writes a string to the text box. A reference to the System.Windows.Forms.dll and System.Drawing.dll namespaces must be added before compiling the project.

As can be seen in Listing 9.2, we create a WinForm class derived from the Form class. After that, we create the Button and TextBox controls. We then set the button and text box properties such as Name, Text, BackgroundColor, ForegroundColor, and Size. The call to the Form.Controls.AddRange method takes an array of controls as a parameter and adds them to the form as indicated in the following code:


        myFrm.Controls.AddRange(new System.Windows.Forms.Control[] { myFrm.textBox1, myFrm.button1 });


An event handler is also created for the Button control. The following code shows how to write a button click event handler for button1. The button1_Click method executes when the button is clicked.


        myFrm.button1.Click += new System.EventHandler(myFrm.button1_Click);


Listing 9.2: Creating a Windows Application with Controls


using
System;
using
System.Windows.Forms;
using
System.Drawing;

public
class WinForm : Form
{
    private Button button1;
    private TextBox textBox1;

    public WinForm()
    {
    }

    static void Main(string[] args)
    {
        WinForm myFrm = new WinForm();

       
// Create Button and TextBox objects
        myFrm.button1 = new System.Windows.Forms.Button();
        myFrm.textBox1 = new System.Windows.Forms.TextBox();

       
// Setting the Button control Properties
        myFrm.button1.BackColor = System.Drawing.Color.Blue;
        myFrm.button1.ForeColor = System.Drawing.Color.Yellow;
        myFrm.button1.Location = new System.Drawing.Point(24, 40);
        myFrm.button1.Name = "button1";
        myFrm.button1.Size = new System.Drawing.Size(112, 32);
        myFrm.button1.TabIndex = 0;
        myFrm.button1.Text = "Click Me";

       
// The button click event handler
        myFrm.button1.Click +=
new
        System.EventHandler(myFrm.button1_Click);

       
// Setting the TextBox control Properties
        myFrm.textBox1.Location = new System.Drawing.Point(168, 48);
        myFrm.textBox1.Name = "textBox1";
        myFrm.textBox1.Size = new System.Drawing.Size(104, 20);
        myFrm.textBox1.TabIndex = 1;
        myFrm.textBox1.Text = "textBox1";

       
// Setting the form Properties
        myFrm.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        myFrm.ClientSize = new System.Drawing.Size(292, 273);
        myFrm.Controls.AddRange(new System.Windows.Forms.Control[] { myFrm.textBox1, myFrm.button1 });
        myFrm.Text = "My First Windows Application";
        myFrm.BackColor = Color.Red;
        myFrm.ForeColor = Color.Yellow;
        myFrm.ResumeLayout(false);
        Application.Run(myFrm);
    }

   
// The button click event handler
    private void button1_Click(object sender, System.EventArgs e)
    {
        textBox1.Text = "Button is clicked";
    }
}


The result of compiling and running the code in Listing 9.2 appears in Figure 9.2, after the button has been clicked.

figure-9.2.gif

Figure 9.2: Creating a Windows Application with Controls

Conclusion


Hope this article would have helped you in understanding Windows Programming in C#. See other articles on the website on .NET and C#.
visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.

Up Next
    Ebook Download
    View all
    Learn
    View all