Windows Forms Winforms
 

What are windows form applications?

Windows form applications are standard applications for Windows operating system having a user interface. A windows form application usually has one or more forms containing menus and other user interface controls like buttons, text boxes, tree view, etc. Windows form applications are like any other application on Windows except that it has its own Graphical User Interface (GUI). Common examples of windows form applications include Microsoft Word, Adobe Photoshop and Winamp. Windows form applications are event based, i.e., they perform certain operations on user action. For example, Microsoft Word saves the document into disk file only when you ask the application to do so (selecting File > Save).

How are the Windows form applications different from the Console Applications?

Windows applications are facilitated with the Windows standard user interface controls (like button, text box, list box, picture box and etc) and the standard events of Windows operating system. On the other hand, the Console Application can only take user input and output from/to the Console, command or a shell window. Windows form applications are more responsive and may use a lot of features like shortcut and icons. On the other hand, console applications are light weight and are used for testing and background service type applications. Several Java based web servers are implemented on Windows using Console application.

How are the Windows form applications different from the Console Applications?

Windows applications are facilitated with the Windows standard user interface controls (like button, text box, list box, picture box and etc) and the standard events of Windows operating system. On the other hand, the Console Application can only take user input and output from/to the Console, command or a shell window. Windows form applications are more responsive and may use a lot of features like shortcut and icons. On the other hand, console applications are light weight and are used for testing and background service type applications. Several Java based web servers are implemented on Windows using Console application.

What support does the Visual Studio.NET provide for the development of .NET win form applications?

Visual Studio.NET provides an enormous support for the development of Win Form applications. The key features of Visual Studio.NET IDE include:

  • The form designer allows you to design the User Interface (UI) of the applications by simple drag and drop of the controls.
  • The Properties window allows you to set different properties for form and a number of windows controls
  • The Intellisense (help completing the syntax as you place dot (.) with objects, enumeration and namespace and when you create new objects)
  • Project and solution management with solution explorer that helps manage applications consisting of multiple files, which is what usually happens
  • Standard debugger that allows you to debug your program by putting break points for observing run-time behavior of the variables and objects in the program
  • Hot compiler that checks the syntax of your code as you type it and report any errors present
  • Dynamic Help on number of topics using Microsoft Development Network (MSDN) Library
  • Compilation and building applications
  • Execution of your application with/without debugger
  • Deploying your .NET application over the Internet or on CDs

How do I make my first “Hello, WinForm” .NET form application using VS.NET and Visual C#?

C# Version Using Visual Studio.NET to build the “Hello WinForm” Application So we have had a lot of Visual Studio.NET introduction. Now, let’s use Visual Studio.NET IDE to build the “Hello WinForm” application which we created earlier in the lesson.

Creating a new Project First of all, we need to create a new C# Windows Application Project. For this, start Visual Studio.NET and click File -> New -> Project. It will show the following screen

[IMAGE1]

From the above screen, select ‘Visual C# Projects’ in Project types and ‘Windows Application’ in Templates. Write the name of the new project (‘LearningWinForm’ in the above figure) in the text box labeled Name. Select the disk path where you wish to store the project using Browse… Button and click OK. It will show you an empty form in the designer view similar to the figure below

[IMAGE2]

The layout of the form designer screen may be somewhat different from the one shown above. Your toolbox and properties window may be visible and some other windows may not be visible. You can change these settings using View menu as described earlier in the lesson.

Setting various properties of the form You can change the default properties of the form using the Properties window. For this, select (click) the form and select the properties window (If the properties window is not visible in the right hand pan, select View -> Properties Window). Now change the title of the form and the name of the form’s class in the code using Text and Form’s Name property respectively as shown in the following figure.

IMAGE3]

Adding Controls to the Form Now select the Label control from toolbox and place it on the form and resize it as appropriate. Select (click) the label on the form and from the properties window, set its Text property to “Hello WinForm” and the Name property to ‘lblGreeting’. The name of a control is the name of its corresponding instance in the source code. Now select the Button control from toolbox and place it on the form and resize it appropriately. Select (click) the button and set its Name property as ‘btnExit’ and Text property as ‘Exit’ from the properties window. The form should now look like

[IMAGE4]

Adding Event Handling Now, we need to add the event handling code for the Exit button. For this, simply double click the Exit button in the designer. It will create a new event handler for the Exit button’s Click event and take you to the source code as shown in the following figure

[IMAGE5]

Write the code to close the application (Application.Exit()) in the event handler. The IDE in fact has not only created the event handler but also has registered it with the Exit button’s Click event.

Executing the application That is it! The ‘Hello WinForm’ application is complete. To compile and execute the application, select Build -> Build Solution (or press Ctrl+Shift+B) and then select Debug -> Start Without Debugging (or press Ctrl+F5).

Author’s Note: Unfortunately, my copy of Visual Studio.NET 2001 does not change the name of form (from Form1 to MyForm in our case) in the call to Application.Run() method in the Main() method. I have to explicitly change the Main() method like this

static void Main() 
{
Application.Run(new MyForm());
}

If you are also experiencing the same problem with your copy of Visual Studio.NET, make sure to change the name of the form in Main() method also whenever you change its name in the Properties Window in order to avoid the compilation error

This will compile and start the ‘Hello WinForm’ application in a new window as shown below

[IMAGE6]

To close the application, click the Exit button or the close button at the title bar of the window.

The code generated by the Form Designer You can toggle between Form Designer and Code using View -> Designer and View -> Code. After switching to the code, you will find the code generated by the form designer to be very similar to that we have written earlier in the lesson. To understand the code better, we recommend removing all the comments and region boundaries.

How do I make my first “Hello, WinForm” .NET form application using VS.NET and Visual Basic.NET?

VB.NET Version Using Visual Studio.NET to build the "Hello WinForm" Application Let's use the Visual Studio.NET IDE to build the "Hello WinForm" application. Creating a new Project First of all, we need to create a new VB.NET Windows Application Project. For this, start Visual Studio.NET and click File -> New -> Project. It will show the following screen:

[IMAGE7]

From the above screen, select 'Visual Basic Projects' in Project types and 'Windows Application' in Templates. Write the name of the new project ('LearningWinForm' in the above figure) in the text box labeled Name. Select the location where you wish to store the project using the Browse... Button and click OK. It will show you an empty form in the designer view similar to the figure below: [IMAGE8]

The layout of the form designer screen may be somewhat different from the one shown above. Your toolbox and properties window may be visible and some other windows may not be visible. You can change these settings using the View menu as described earlier in the lesson.

Setting various properties of the form You can change the default properties of the form using the Properties window. For this, select (click) the form and select the properties window (If the properties window is not visible in the right hand pane, select View -> 'Properties Window). Now change the title of the form and the name of the form's class in the code by changing the Text and Name properties, as shown in the following figure.

[IMAGE9]

Adding Controls to the Form Now select the Label control from the toolbox, place it on the form and resize it as appropriate. Select (click) the label on the form and from the properties window, set its Text property to "Hello WinForm" and the Name property to 'lblGreeting'. The name of a control is the name of its corresponding instance in the source code. Now select the Button control from the toolbox, place it on the form and resize it appropriately. Select (click) the button and set its Name property to 'btnExit' and its Text property to 'Exit' using the properties window. The form should now look like this:

[IMAGE10] Adding Event Handling Now we need to add the event handling code for the Exit button. For this, simply double click the Exit button in the designer. This will create a new event handler for the Exit button's Click event and take you to the source code as shown in the following figure:

[IMAGE11] Write the code to close the application (Application.Exit()) in the event handler. The IDE in fact has not only created the event handler but also has registered it with the Exit button's Click event. Executing the application That is it! The 'Hello WinForm' application is complete. To compile and execute the application, select Build ->Build Solution (or press Ctrl+Shift+B) and then select Debug -> Start Without Debugging (or press Ctrl+F5). This will compile and start the 'Hello WinForm' application in a new window as shown below:

[IMAGE12] To close the application, click the Exit button or the close button on the title bar of the window. The code generated by the Form Designer You can toggle between the Form Designer and Code using View -> Designer and View -> Code. After switching to the code, you will find the code generated by the form designer to be very similar to that we have written earlier in the lesson. To understand the code better, we recommend removing all the comments and region boundaries.

What is the architecture of .NET win form applications?

C# Version

WinForm Architecture As stated earlier, .NET provides WinForm and other controls through base classes in the System.Windows.Forms namespace. The class System.Windows.Forms.Form is the base class of all WinForms in .NET. In order to design a windows application, we need: 1. Create a Windows Application project in Visual Studio.NET or add references to System.Windows.Forms and System.Drawing to your current project. If you are not using Visual Studio at all, use /reference option of the command line compiler to add these assemblies. 2. Write a new class to represent the WinForm and derive it from System.Windows.Forms.Form class as

class MyForm : System.Windows.Form
{
...
}

3. Instantiate various controls, set their appropriate properties and add these to MyForm’s Controls collection. 4. Write another class containing the Main() method. In the Main() method, call the System.Application.Run() method by supplying it an instance of MyForm.

class Test
{
static void Main()
{
Application.Run(new MyForm());
}
}

The Application.Run() method registers your form as a windows application in the operating system so that it may receive event messages from the Windows Operating System.

VB.NET Version

WinForm Architecture As stated earlier, .NET provides the WinForm and other controls through base classes in the System.Windows.Forms namespace. The class System.Windows.Forms.Form is the base class of all WinForms in .NET. In order to design a windows application, we need to: 1.Create a Windows Application project in Visual Studio.NET, or add references to System.Windows.Forms and System.Drawing to your current project. If you are not using Visual Studio at all, use the /reference option of the command line compiler to add these assemblies. 2. Write a new class to represent the WinForm and derive it from the

System.Windows.Forms.Form class: 
Public Class MyForm
Inherits System.Windows.Forms.Form 
End Class

3. Instantiate various controls, set their appropriate properties and add these to MyForm's Controls collection. 4. Write another class containing the Main() method. In the Main() method, call the System.Application.Run() method, supplying it with an instance of

MyForm. 
Class Test
Public Sub Main()
Application.Run(New MyForm())
End Sub

End Class

The Application.Run() method registers your form as a windows application in the operating system so that it may receive event messages from the Windows Operating System.

Index

How do I make my first “Hello, WinForm” .NET form application without VS.NET in Visual C#?

C# Version

Building the “Hello WinForm” Application Let’s now build our first windows application called “Hello WinForm”. The application will present a simple window with “Hello WinForm” greeting at the center. The source code of the program is:

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

namespace CSharpSchool

{

class Test

{

static void Main()

{

Application.Run(new MyWindow());

}

}

class MyWindow : Form

{

public MyWindow() : base()

{

this.Text = "My First Windows Application";

this.Size = new Size(300, 300);

Label lblGreeting = new Label();

lblGreeting.Text = "Hello WinForm";

lblGreeting.Location = new Point(100, 100);

this.Controls.Add(lblGreeting);

}

}

}

Understanding the Code

In the start, we included three namespaces to our application

using System;

using System.Windows.Forms;

using System.Drawing;

The System namespace, as we stated in the first lesson, is the necessary ingredient of all C# applications. In fact, the Application class that we used later in the Main() method is defined in this namespace. The System.Windows.Forms namespaces contains the base classes for windows controls like Form, Label and Button. Finally, including the System.Drawing namespace is necessary as it contains the useful classes related to the drawing of controls. The Size and Point classes used later in the program are actually defined in System.Drawing namespace.

Later, we derived a new class ‘MyWindow’ from the Form class defined in

System.Windows.Forms 
class MyWindow : Form
{
...
}

In the constructor of MyWindow, we specified the size and title of the form. The size is defined using the System.Drawing namespace’s Size class. We passed two integers to the constructor of Size to specify the width and the height of the form.

public MyWindow() : base()
{
this.Text = "My First Windows Application";
this.Size = new Size(300, 300);

Next in the constructor, we created a text label and added it to the Controls collection of the Form. A text label is used to write some text on the form. The System.Windows.Forms.Label class is used to create a text label in windows applications. We set the text of the Label using its Text property which is of string type. All the controls contained by a form must be added to its Controls collection; hence we have also added our label to this collection.

public MyWindow() : base()
{
this.Text = "My First Windows Application";
this.Size = new Size(300, 300);

Label lblGreeting = new Label();

lblGreeting.Text = "Hello WinForm";

lblGreeting.Location = new Point(100, 100);

this.Controls.Add(lblGreeting);

}

Finally, we have created a Test class containing the Main() method. In the Main() method, we have instantiated the MyWindow class and passed its reference to the Application.Run() method so it may receive messages from the Windows Operating System.

When we execute the above code, the following screen is presented as output

To close the application, press the close button on the title bar.

Adding Event Handling Let’s now add a button labeled ‘Exit’ to the form. The ‘Exit’ button will close the application when it is clicked. In .NET, Push Buttons are instances of the System.Windows.Forms.Button class. To associate some action with the button click, we need to create an event handler and register (or add) it to the Button’s Click event. Following is the code for this modified application

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

namespace CSharpSchool

{

class Test

{

static void Main()

{

Application.Run(new MyWindow());

}

}

class MyWindow : Form

{

public MyWindow() : base()

{

// Form

this.Text = "My First Windows Application";

this.Size = new Size(300, 300);

this.StartPosition = FormStartPosition.CenterScreen;

// Label

Label lblGreeting = new Label();

lblGreeting.Text = "Hello WinForm";

lblGreeting.Location = new Point(100, 100);

// Button

Button btnExit = new Button();

btnExit.Text = "Exit";

btnExit.Location = new Point(180, 180);

btnExit.Size = new Size(80, 30);

btnExit.Click += new EventHandler(BtnExitOnClick);

// Adding controls to Form

this.Controls.AddRange(new Control[] {lblGreeting, btnExit});

}

public void BtnExitOnClick(object sender, EventArgs e)

{

Application.Exit();

}

}

}

In the constructor of MyWindow, first we have set certain properties of the Form. In this code, we have also used the StartPosition property of the Form, which sets the start up position of the form on the screen. The type of this property is an enumeration called ‘FormStartPosition’. We have set the start position of the form to the center of the screen.

The new inclusion in the code is the Exit button called ‘btnExit’. We have created the button using the base class System.Windows.Forms.Button. Later, we set various properties of the button like its text label (Text), its Location and its Size. Finally, we have created an event handler method for this button called BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to exit the application. We have also registered this event handler to the btnExit’s Click event (To understand the event handling in C#, see lesson 10 of the C# school). In the end, we have added a label and button to the form’s Controls collection. Note that this time we have used AddRange() method of form class to add an array of controls to the Controls collection of form. This method takes an array of type Control as its parameter.

The output of the code will be

Now you can press either the Exit Button or the close button at title bar to exit the application.

How do I make my first “Hello, WinForm” .NET form application without VS.NET in Visual Basic.NET?

VB.NET Version

Building the "Hello WinForm" Application Let's build our first windows application, which we will call "Hello WinForm". The application will present a simple window with a "Hello WinForm" greeting at the center. The source code of the program is:

Imports System
Imports System.Windows.Forms
Imports System.Drawing

Class Test

Public Sub Main()

Application.Run(New MyForm())

End Sub

End Class

Class MyForm

Inherits Form

Public Sub New()

MyBase.new()

Me.Text = "My First Windows Application"

Me.Size = New Size(300, 300)

Dim lblGreeting As New Label()

lblGreeting.Text = "Hello WinForm"

lblGreeting.Location = New Point(100, 100)

Me.Controls.Add(lblGreeting)

End Sub

End Class

Understanding the Code At the start, we included three namespaces in our application:

Imports System
Imports System.Windows.Forms
Imports System.Drawing

The System namespace, as we stated in the first lesson, is the necessary ingredient of all VB.NET applications. In fact, the Application class that we used later in the Main() method is defined in this namespace. The System.Windows.Forms namespaces contains the base classes for windows controls, e.g. Form, Label and Button. Finally, including the System.Drawing namespace is necessary as it contains the classes related to the drawing of controls. The Size and Point classes used later in the program are actually defined in the System.Drawing namespace. The System.Windows.Forms and System.Drawing namespaces can not be added to a project just by writing Imports statement for them. We also need to add references to the assemblies (for now take assemblies as Windows DLL’s or library files for .NET) that contain the code of types these namespaces. For this we need to add reference to System.Windows.Forms.dll and System.Drawing.dll. To add a reference write click the ‘Reference’ folder under the current project in the solution explorer and select Add Reference… It will show the following window

From the '.NET' tab of the Add Reference Dialog box, select the System.Windows.Forms.dll and System.Drawing.dll and select OK. This completes the process of adding references to assemblies in your project. Lets go back to our sample application. Later, we derived a new class, 'MyForm', from the Form class defined in

System.Windows.Forms. 
Class MyForm
Inherits Form
...

End Sub

End Class

In the constructor of MyForm, we specified the size and title of the form (by setting the size and text properties). The size is defined using the System.Drawing namespace's Size class. We passed two integers to the constructor of Size to specify the width and the height of the form.

Public Sub New()
MyBase.new()
Me.Text = "My First Windows Application"
Me.Size = New Size(300, 300)

Next in the constructor, we created a text label and added it to the Controls collection of the Form. A text label is used to write some text on the form. The System.Windows.Forms.Label class defines a text label in a Windows application. We set the text of the Label using its Text property, which is of the string type. All the controls contained by a form must be added to its Controls collection; hence we have also added our label to this collection.

Public Sub New()
MyBase.new()
Me.Text = "My First Windows Application"
Me.Size = New Size(300, 300)

Dim lblGreeting As New Label()

lblGreeting.Text = "Hello WinForm"

lblGreeting.Location = New Point(100, 100)

Me.Controls.Add(lblGreeting)

End Sub

Finally, we have created a Test class containing the Main() method. In the Main() method, we have instantiated the MyForm class and passed its reference to the Application.Run() method so it may receive messages from the Windows Operating System. When we execute the above code, the following screen is displayed: To close the application, press the close button on the title bar.

Adding Event Handling Let's now add a button labeled 'Exit' to the form. The 'Exit' button will close the application when it is clicked. In .NET, Push Buttons are instances of the System.Windows.Forms.Button class. To associate some action with the button click, we need to create an event handler and register (or add) it to the Button's Click event. Below is the code for this application.

Imports System
Imports System.Windows.Forms
Imports System.Drawing

Class Test

Public Sub Main()

Application.Run(New MyForm())

End Sub

End Class

Class MyForm

Inherits Form

Public Sub New()

MyBase.new()

' Form

Me.Text = "My First Windows Application"

Me.Size = New Size(300, 300)

' Label

Dim lblGreeting As New Label()

lblGreeting.Text = "Hello WinForm"

lblGreeting.Location = New Point(100, 100)

' Button

Dim btnExit As New Button()

btnExit.Text = "Exit"

btnExit.Location = New Point(180, 180)

btnExit.Size = New Size(80, 30)

AddHandler btnExit.Click, AddressOf BtnExitOnClick

Me.Controls.AddRange(New Control() {lblGreeting, btnExit})

End Sub

Public Sub BtnExitOnClick(ByVal sender As Object, ByVal e As EventArgs)

Application.Exit()

End Sub

End Class

In the constructor of MyForm, first we have set certain properties of the Form. In this code, we have also used the StartPosition property of the Form, which sets the position of the form on the screen when the application starts. The type of this property is an enumeration called 'FormStartPosition'. We have set the start position of the form to the center of the screen. The new inclusion in the code is the Exit button called 'btnExit'. We have created the button using the base class System.Windows.Forms.Button. Later, we have set various properties of the button, specifically its text label (Text), its Location and its Size. Finally, we have created an event handler method for this button called BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to exit the application. We have also subscribed this event handler to the btnExit's Click event (To understand the event handling in VB.Net, see lesson 10 of the VB.Net school). In the end, we have added both the label and the button to the form's Controls collection. Note that this time we have used the AddRange() method of form class to add an array of controls to the Controls collection of form. This method takes an array of type Control as its parameter. When the code is run, the following window will be displayed: Now you can press either the Exit Button or the close button at title bar to exit the application.

Alternate procedure for Event Handling – Using the ‘Handles’ Keyword Note that in the previous code, we subscribed Exit buttons event handler using the ‘AddHandler’ keyword. We can also do this using the ‘Handles’ keyword with the Event Handler method. But to use the ‘Handles’ keyword, the Exit button needs to be instance variable of the form class defined with the ‘WithEvents’ keyword. The complete source code of the MyForm class is

Class MyForm
Inherits Form

' Form controls are usually private

' instance members of the form class

Private WithEvents btnExit As New Button()

Private lblGreeting As New Label()

Public Sub New()

MyBase.new()

' Form

Me.Text = "My First Windows Application"

Me.Size = New Size(300, 300)

' Label

lblGreeting.Text = "Hello WinForm"

lblGreeting.Location = New Point(100, 100)

' Button

btnExit.Text = "Exit"

btnExit.Location = New Point(180, 180)

btnExit.Size = New Size(80, 30)

'AddHandler btnExit.Click, AddressOf BtnExitOnClick

Me.Controls.AddRange(New Control() {lblGreeting, btnExit})

End Sub

Public Sub BtnExitOnClick(ByVal sender As Object, ByVal e As EventArgs) Handles btnExit.Click

Application.Exit()

End Sub

End Class

This procedure of event handling (using the ‘Handles’ keyword) is usually followed by Visual Studio.NET standard code for Form based applications (Windows and Web Applications)

How do I provide the event handling for my form and controls using VS.NET?

Adding Event Handling You can provide event handling for forms and controls by implementing their respective event handlers. To implement an event handler for a form or control, go to Events tab of the properties window, and double click the desired event handler name. The form designer will add the event handler for the selected event in the source code of the application and take you there. If you want to implement a default event handler of the form or control, simply double click it.

For example, to add the event handling code for the Exit button in the Hello WinForm application (demonstrated in FAQ 5), simply double click the Exit button in the designer. It will create a new event handler for the Exit button’s Click event and take you to the source code as shown in the following figure

C# Version

Write the code to close the application (Application.Exit()) in the event handler. The IDE in fact has not only created the event handler but also has registered it with the Exit button’s Click event.

How event handling is implemented in win form and .NET form controls with C#?

C# Version

Adding Event Handling A control exposes an event by defining its delegate. We can add our own event handler for the event by writing an event handler method and adding it to the event’s delegate.

For example, add a button labeled ‘Exit’ to the form of FAQ 8. The ‘Exit’ button will close the application when it is clicked. In .Net, Push Buttons are instances of the System.Windows.Forms.Button class. To associate some action with the button click, we need to create an event handler and register (or add) it to the Button’s Click event. Following is the code for this modified application

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

namespace CSharpSchool

{

class Test

{

static void Main()

{

Application.Run(new MyWindow());

}

}

class MyWindow : Form

{

public MyWindow() : base()

{

// Form

this.Text = "My First Windows Application";

this.Size = new Size(300, 300);

this.StartPosition = FormStartPosition.CenterScreen;

// Label

Label lblGreeting = new Label();

lblGreeting.Text = "Hello WinForm";

lblGreeting.Location = new Point(100, 100);

// Button

Button btnExit = new Button();

btnExit.Text = "Exit";

btnExit.Location = new Point(180, 180);

btnExit.Size = new Size(80, 30);

btnExit.Click += new EventHandler(BtnExitOnClick);

// Adding controls to Form

this.Controls.AddRange(new Control[] {lblGreeting, btnExit});

}

public void BtnExitOnClick(object sender, EventArgs e)

{

Application.Exit();

}

}

}

We have highlighted the interested parts in the above code by bold formatting. We have created the Exit button called ‘btnExit’ using the class System.Windows.Forms.Button. Later, we set various properties of the button like its text label (Text), its Location and its Size. Finally, we have created an event handler method for this button called BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to exit the application. We have also registered this event handler to the btnExit’s Click event (To understand the event handling in C#, see lesson 10 of the C# school). In the end, we have added a label and button to the form’s Controls collection.

The output of the code will be

Now you can press either the Exit Button or the close button at title bar to exit the application.

How event handling is implemented in win form and .NET form controls with VB.NET?

VB.NET Version

Adding Event Handling A control exposes an event by defining its ‘delegate’. We can add our own event handler for the event by writing an event handler method and adding it to the event's delegate. Let's add a button labeled 'Exit' to the form. The 'Exit' button will close the application when it is clicked. In .Net, Push Buttons are instances of the System.Windows.Forms.Button class. To associate some action with the button click, we need to create an event handler and register (or add) it to the Button's Click event. Below is the code for this application.

Imports System
Imports System.Windows.Forms
Imports System.Drawing

Class Test

Public Sub Main()

Application.Run(New MyForm())

End Sub

End Class

Class MyForm

Inherits Form

Public Sub New()

MyBase.new()

' Form

Me.Text = "My First Windows Application"

Me.Size = New Size(300, 300)

' Label

Dim lblGreeting As New Label()

lblGreeting.Text = "Hello WinForm"

lblGreeting.Location = New Point(100, 100)

' Button

Dim btnExit As New Button()

btnExit.Text = "Exit"

btnExit.Location = New Point(180, 180)

btnExit.Size = New Size(80, 30)

AddHandler btnExit.Click, AddressOf BtnExitOnClick

Me.Controls.AddRange(New Control() {lblGreeting, btnExit})

End Sub

Public Sub BtnExitOnClick(ByVal sender As Object, ByVal e As EventArgs)

Application.Exit()

End Sub

End Class

The interesting lines defining the event handler for the button is highlighted with bold formatting. We have created an event handler method for this button called BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to exit the application. We have also subscribed this event handler to the btnExit's Click event (To understand the event handling in VB.NET, see lesson 10 of the VB.NET school). Now you can press either the Exit Button or the close button at title bar to exit the application. Alternate procedure for Event Handling – Using the ‘Handles’ Keyword Note that in the previous code, we subscribed Exit buttons event handler using the ‘AddHandler’ keyword. We can also do this using the ‘Handles’ keyword with the Event Handler method. But to use the ‘Handles’ keyword, the Exit button needs to be instance variable of the form class defined with the ‘WithEvents’ keyword. The complete source code of the MyForm class is

Class MyForm
Inherits Form

' Form controls are usually private

' instance members of the form class

Private WithEvents btnExit As New Button()

Private lblGreeting As New Label()

Public Sub New()

MyBase.new()

' Form

Me.Text = "My First Windows Application"

Me.Size = New Size(300, 300)

' Label

lblGreeting.Text = "Hello WinForm"

lblGreeting.Location = New Point(100, 100)

' Button

btnExit.Text = "Exit"

btnExit.Location = New Point(180, 180)

btnExit.Size = New Size(80, 30)

'AddHandler btnExit.Click, AddressOf BtnExitOnClick

Me.Controls.AddRange(New Control() {lblGreeting, btnExit})

End Sub

Public Sub BtnExitOnClick(ByVal sender As Object, ByVal e As EventArgs) Handles btnExit.Click

Application.Exit()

End Sub

End Class

Note that the button is now instantiated with the ‘WithEvents’ keyword and the event handler is specifically marked with the ‘Handles’ keyword to qualify it as an event handler method. This procedure of implementing event handling (using the ‘Handles’ keyword) is usually followed by Visual Studio.NET standard code for Form based applications (Windows and Web Applications)

What are the lifetime events of a form?

Some important lifetime events of a form include:

Load: This event is fired when the form is first loaded in the program. It is called when the Form.Show() or Form.ShowDialog() method is called for the first time.

Activated: This event is triggered whenever the form gets the application focus. It is fired when the form is first loaded (along with Load event), when the form is brought in front, or when the form is restored from the minimized state.

VisibleChanged: It is called whenever the Visible property of the form is changed or the form is hidden or shown.

Deactivated: This event is triggered whenever the form loses the application focus. It is fired when the form is closed, when the form is brought into background, or when the form is minimized.

Closing: It is fired when the application wishes to be closed, or the application is in the process of close but has not yet closed.

Closed: It is raised when the application is finally closed.

How do I change the title of my window?

Use the Text property of the Form to change the title of the form.

How do I change the application name?

To change the application name, change the name of the startup project by right clicking the project node in the solution explorer and selecting properties. It will show the property pages for the project. Here in the Common Properties -> General, you can change the assembly name to change the resulting executable (.exe) file name.

How do I set the startup position of the form?

To change the startup position of the form, select the form in the designer and change its StartPosition property. The StartPosition is an enumeration and has the following useful properties:

CenterScreen: The form should be displayed at the center of the screen
WindowsDefaultLocation: The form's startup position should be selected by the Windows Operating System
CenterParent: The form should be displayed at the center of the parent form. This option is useful when you are building an MDI (Multiple Document Interface) application. The MDI child form can be set, in this way, to be displayed at the center of the MDI parent form.

How do I set the initial (startup) size of the form?

The size property can be used to set the startup size of the form. The data type of the size property is System.Drawing.Size. The size can be set as:

C# Version

myForm.Size = new System.Drawing.Size(400, 300);

VB.NET Version

myForm.Size = New System.Drawing.Size(400, 300)

What does it mean by Startup Window State of the form? How do I set the startup window state of the form?

The startup window state specifies whether the form should be displayed in normal, maximized or minimized state. It can be set using the WindowState property of the form. The data type of this property is System.Windows.Forms.FormWindowState enumeration, which has three members; Maximized, Minimized and Normal.

C# Version

myForm.WindowState = FormWindowState.Maximized;

VB.NET Version

myForm.WindowState = FormWindowState.Maximized

How do I hide my form?

You can hide your form or any other control by setting its Visible property to False.

C# Version

myForm.Visible = False;

VB.NET Version

myForm.Visible = False

How do I show my form?

You can show your hidden form or any other control by setting its ‘Visible’ property to True.

C# Version

myForm.Visible = True;

VB.NET Version

myForm.Visible = True

You can also display your form for the first time using the Show() or the ShowDialog() methods of the form class. The Show() method displays the form in Non-Modal fashion, while the ShowDialog() method displays the form in Modal mode. See the following FAQs for the description of Modal and Non-Modal forms

What is the difference between modal and non-modal dialogs?

The modal form, when displayed on the screen, does not allow you to go and select any other form of the window. The typical example of the Modal form is the Message Box; you must select OK (or other appropriate) button to go back to other forms of the applications.

The Non modal form, on the other hand, does not prevent you from accessing other form windows of the application, when they are present on the screen using the Show() method of the form.

C# Version

myForm.Show();

VB.NET Version

myForm.Show()

By default, all the forms are Non-modal.

How do I show my form as a modal dialog?

To show your form as the Modal dialog, call the ShowDialog() method of the form to display it on the screen.

C# Version

myForm.ShowDialog();

VB.NET Version

myForm.ShowDialog()

It will display the form as a Modal dialog and would not allow the user to access any other form of the application when it is present on the screen.

How do I minimize, maximize and restore my form programmatically?

You can minimize, maximize and restore the form by setting the WindowState property of the form. The following code example will minimize the form, wait for 2 seconds, restore the form, wait for 2 seconds and then maximize the form. I have written this code on the a button’s Click event.

C# Version

private void button1_Click(object sender, System.EventArgs e)
{
// Minimize the form window
this.WindowState = FormWindowState.Minimized;

Thread.Sleep(2000);// wait for 2 seconds

// Restore the form window

this.WindowState = FormWindowState.Normal;

Thread.Sleep(2000);// wait for 2 seconds

// Maximize the form window

this.WindowState = FormWindowState.Maximized;

}

VB.NET Version

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click

' Minimize the form window

Me.WindowState = FormWindowState.Minimized

Thread.Sleep(2000)' wait for 2 seconds

' Restore the form window

Me.WindowState = FormWindowState.Normal

Thread.Sleep(2000)' wait for 2 seconds

' Maximize the form window

Me.WindowState = FormWindowState.Maximized

End Sub

Note that the above code snippet is using the System.Threading.Thread class’ Sleep method to suspend the form for 2 seconds. Hence, you would be required to include the System.Threading namespace to your form class source code.

C# Version

Using System.Threading;

VB.NET Version

Imports System.Threading

How do I hide maximize, minimize and close box at the form title bar?

To disable the maximize box at the form title bar, set the Maximize property of the form to false.

To disable the minimize box at the form title bar, set the Minimize property of the form to false.

You can not hide only the close box from the form title bar using the form’s property.

Similarly, you can not only hide maximize or minimize boxes from the title window.

You can hide maximize and minimize boxes from the title bar by setting the FormBorderStyle property of the form to the FixedToolWindow or the SizableToolWindow. But remember that with FormBorderStyle set to the FixedToolWindow or SizableToolWindow, the form will not be displayed in the Windows task bar or in the window that appears when the user presses ALT+TAB.

You can hide the Control box from the title bar of the form by setting the ControlBox property of the form to false. This will hide the control box and system menu from the form window.

How do I make my form non-resizable or fixed length?

You can make your form non-resizable or fixed length by setting its FormBorderStyle property to Fixed3D or FixedSingle or FixedDialog

How do I change the icon of my form to be displayed at title bar?

You can change the icon of the form by changing its icon property. Remember that this property will only change the icon of the form and not of the application. To change the icon of the application or assembly, change the icon from the property pages of the project. The property pages for the project are displayed when you right click the project and select properties.

How do I make my form not to appear in the task bar?

To make your form not to appear in the task bar, set the ShowInTaskbar property of the form to false.

How do I make and display a form without title bar?

To display your from without the title bar, set the FormBorderStyle property of the form to None

How do I close the form programmatically?

To close the form programmatically, call the Close() method of the form.

C# Version

myForm.Close();

VB.NET Version

myForm.Close()

Remember that this will only close the form and not the application. To close or exit the application, call the Application.Exit() method.

How do I exit my win form application programmatically?

To exit the win form application programmatically, call the Application.Exit() method.

C# Version

Application.Exit();

VB.NET Version

Application.Exit()

How do I display a message box in my form application?

To show the message box, call the MessageBox class’ Show() method. The message box is the modal form that notifies the user about certain event in the application and optionally takes the user feedback. The Show() is an static (C#) / Shared (VB.NET) method of the System.Windows.Forms.MessageBox class. It has a number of overloaded versions. The simplest one take the message text and display it in the message box.

C# Version

MessageBox.Show("Welcome to Win Form");

VB.NET Version

MessageBox.Show("Welcome to Win Form")

To add the title to the message box, call the MessageBox.Show() like:

C# Version

MessageBox.Show("Welcome to Win Form", "Greeting");

VB.NET Version

MessageBox.Show("Welcome to Win Form", "Greeting")

The following example code shows the message box with Yes, No, Cancel button to confirm application close and closes the application if the user selects the Yes button

C# Version

DialogResult dlgRes = null
dlgRes = MessageBox.Show(
"Are you sure you want to close without saving the document", 
"Confirm Document Close", 
MessageBoxButtons.YesNoCancel, 
MessageBoxIcon.Question);

if(dlgRes == DialogResult.Yes)

{

Application.Exit();

}

VB.NET Version

Dim dlgRes As DialogResult
dlgRes = MessageBox.Show( _
"Are you sure you want to close without saving the document", _
"Confirm Document Close", _
MessageBoxButtons.YesNoCancel, _
MessageBoxIcon.Question)

If dlgRes = DialogResult.Yes Then

Application.Exit()

End If

How do I add another form into my win form application?

To add and design a new form at design time, right click the target project node in the Solution Explorer and select AddàAdd Windows Form… This will add a new form; design it by placing controls and setting necessary properties.

To show the new form at run time, instantiate the new form and call its Show() or ShowDialog() method.

Let we name the new form as ‘MySecondForm’, then on the click event of the button of our first (startup) form, we can write the following code:

C# Version

MySecondForm frm2 = new MySecondForm();
frm2.Show();// will present the non-modal form

// frm2.ShowDialog(); // will present the modal form

VB.NET Version

Dim frm2 As New MySecondForm()
frm2.Show()' will present the non-modal form

' frm2.ShowDialog() 'will present the modal form

How do I set the first form to be loaded at application startup?

The first form to be loaded at the application startup is called the startup or main form of the application. You can set the startup form of the application by right clicking the target project node and selecting properties. It will show you the property pages for the project. Here in the Common PropertiesàGeneral, you can set the startup form by selecting its name from the drop down list of ‘Startup Object’.

C# Note

Remember that only those forms that have a valid Main() method can be selected as the startup object.

What does it mean by scrollable forms in .NET? How can make my own form scrollable?

.NET introduces with it a concept of scrollable forms. A scrollable form is just like an html page that can be scrolled. You can access its controls by scrolling it down or right; if the contents (controls) don’t fit in the form display area.

You can make a form scrollable by setting its AutScroll property to true

How do I make a splash screen in my win form application?

There is no built-in support for the splash screen in the Microsoft.NET win form applications. However, you can create a splash screen by creating a form with no title bar (by setting its FormBorderStyle to None), making it not appear in the taskbar (by setting its ShowInTaskbar property to false), making it the top most form (by setting) its TopMost property to true, and making it appear on the center of the screen (by setting its StartupPosition as CenterScreen).

You can now show this splash form when the main application is loading.

C# Version

private void Form1_Load(object sender, System.EventArgs e)
{
this.Hide();
Form2 frmSplash = new Form2();
frmSplash.Show();
frmSplash.Update();
Thread.Sleep(5000);
frmSplash.Close();
this.Visible = true;
}

VB.NET Version

Private Sub Form1_Load(ByVal sender As System.Object, _
yVal e As System.EventArgs) Handles MyBase.Load

Me.Hide()

Dim frmSplash As New Form2

frmSplash.Show()

frmSplash.Update()

Thread.Sleep(5000)

frmSplash.Close()

Me.Visible = True

End Sub

What basics should be remembered while developing win form apps?

Some Important Points for designing Windows Applications

  • Make your form layout simple and easy to understand. It is important that the user of your application finds it familiar. The behavior should be expected and should not surprise the user.
  • The Format menu of the Visual Studio.NET IDE is very useful when designing the form layout. It provides a number of useful options for alignment and size of the controls.
  • Almost all the controls have some similar properties like Location, Size, Enabled, Visible, TabIndex, etc. The TabIndex property is very important. It describes the sequence followed by the windows focus when the user presses the Tab button of keyboard.
  • Usually we don't change the Name property of labels as we don’t need to use the label variable in our code most of the time.
  • The controls should be named so that their purpose can be recognized, e.g., you may name the ‘Purchase’ button as btnPurchase, text box for entering email may be txtEmail and so on.
  • Although now it is not a standard convention, but it is useful to add a three letter prefix to the name of your controls so that they are recognizable with their name. Most of the developers used to follow the convention like prefixing Label with lbl (lblGreeting), TextBox with txt (txtComments), Button with btn (btnPurchase), CheckBox with cbx (cbxProgCS), RadioButton with rbn (rbnFullPayment) and GroupBox with gbx (gbxPaymentMode).

How do I change the icon of the application I am working with?

Changing the Icon of your application is simple. Select Project->Properties. In the windows "style" section click on the "Icon" Button. Then make your choice.

How do I prevent a user from resizing a form?

The following code shows how a Form's size can be restricted at runtime.

Place the following code in the load event of the form.

Public Class Form2
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Me.MaximizeBox = False

End Sub

End Class