Você está na página 1de 15

CSharp.

NET Tutorial Day 15

In previous article, we have discussed what are Exceptions, what is Exception


Handling mechanism, what are Compile time errors, what are Runtime errors,
what is Abnormal Termination of the Program, what is try, catch, and finally
blocks and interrelation in between try, catch and finally, what are System
Exceptions, what are Application Exceptions, who to throw an exception
along with syntaxes and examples, etc

Please find below the link for accessing the article

CSharp.NET Tutorial - Day 14

Now, in this article we will discuss what is Windows Programming, what is


Character User Interface (CUI), what is Graphical User Interface (GUI),
difference between CUI and GUI, How to Develop Windows Applications, what
are Partial Classes, How to Develop a Windows Application using Visual
Studio, what are Properties, what are Events, what are Event Procedures,
How to Define Event Procedures Manually, How to Set Properties and Define
Event Procedure Manually, How to Add a New Form, How to Bind an Event
Procedure with Multiple Events of a Control in Visual Studio, How to Place
Controls on the Form, How to Bind an Event Procedure with Multiple Controls,
How does a Form gets created, How does a control gets placed on the Form,
what are types of code In Windows application, definitions of Designer Code
and Business Logic along with syntaxes and examples, etc

Windows Programming
Generally, we should require user interface (UI) in order to communicate with
end users in developing any kind of application. For this, we have two
different types of User Interfaces available, which are below.

Character User Interface (CUI)

Graphical User Interface (GUI)

Traditionally, we have only Character User Interface (CUI) available


Eg: DOS, UNIX Operating System, etc
But, these applications suffer from few criticisms like
They are not user friendly because we need to learn the commands
first in order to use them
Also, they do not allow to navigate from one place to other place
To solve the above problems, in early 90's Graphical User Interface (GUI)
applications were introduced by Microsoft with its Windows Operating
System. It has beautiful features known as "Look and Feel." In order to
develop those kind of features, Microsoft has introduced a language into the
market in 90's which is Visual Basic (VB). Afterwards, when .NET was
introduced the support for GUI has been given in all .NET languages.
How to Develop Windows Applications
In order to develop windows application, we require a set of components
called as 'controls.' For us, the controls were provided in .NET in form of
'classes,' where every control acts like a 'class' under the namespace of
"System.Windows.Forms". Here, Controls available to us are divided into
different categories like 'Container Controls, 'Menu and Toolbar Controls,'
'Data Controls, 'Printing Controls, 'Reporting Controls,' etc for easy identity.
Note: Here, each and every 'Control' available is a Subclass of a Class called
'Control' and it will provide the common features which are necessary for
each control.
There are mainly three things in common for every Control that we use in
Windows application, which are as follows:
1) Properties
2) Methods
3) Events
Now, we will see one by one
Properties: Here, Properties are the attributes of a Control, which have
their impact on look of a Control.
Eg: Width, Height, BackColor, ForeColor, etc
Methods: Methods are nothing but Actions performed by Controls.

Eg: Clear, Close, Focus, etc


Events: Events tells when an appropriate action has to be performed.
Eg: Click, Load, KeyPress, MouseOver, etc
Now, we clear what are the things we need to remember when developing a
windows application.
To develop a Windows application, first we need to create the Base control
i.e. 'Form'.
To create Form, we need to adopt the below process.

Define a Class which is inheriting from predefined class 'Form' so that


the new class will also act like a 'Form'.
Eg: public class MyForm : Form

To run the Form that we created, first we need to create object of


'Form' and it should pass it as a parameter to 'Run' method which is
present under Application Class. Here, Application Class is responsible
for execution of the 'Form'.
Eg:
MyForm f = new MyForm( );
Application.Run(f);
or
Application.Run(new MyForm ());

Tip: We can develop Windows Application using either with Notepad or with
'Visual Studio' Windows Form Application Project Template.
First, we will see how to develop Windows Application using Notepad
Just open a Notepad and write the below code in it and then Save - Compile Execute
using System;
using System.Windows.Forms;
public class MyForm:Form
{
static void Main()
{
MyForm f=new MyForm ();
Application.Run (f);

}
}

Partial Classes
Partial Classes is the concept of allowing splitting a class and defining it
under multiple files. Here, the advantage is that huge volumes of code can
be put on different files so that manageability becomes much easier.
It also allows many programmers to work on the same class at the same
time.

When we are defining partial classes, we can split them into any number of
files, but the condition is on each file the class name should be the same and
we should use the modifier, 'partial.'
The another advantage is if we want to inherit from any other class we can
do it in only one single file and it will take to the complete class. The reason
why is here the class is physically separated into multiple files, but logically it
is only one.
To check this, add a code file in the project naming it as "Part1.cs" and write
the following.
using System;
namespace OOPSProject
{
partial class Parts
{
public void Method1()
{
Console.WriteLine("Method1");

}
public void Method2()
{
Console.WriteLine("Method2");
}
}
}
Add a Code file 'Part2.cs' and the write the below code.
using System;
namespace OOPSProject
{
partial class Parts
{
public void Method3()
{
Console.WriteLine("Method3");
}
public void Method4()
{
Console.WriteLine ("Method4");
}
}
}
Add a class 'TestParts.cs' and write the below code.
using System;
namespace OOPSProject
{
class TestParts
{
static void Main()
{
Parts p = new Parts ();
p.Method1 (); p.Method2 ();
p.Method3 (); p.Method4 ();
Console.ReadLine ();
}
}
}
How to Develop a Windows Application using Visual Studio

To develop a Windows Application using Visual Studio, open new


project window -> select 'Windows Forms Application' template and
specify a name to the Project.(Eg:- WindowsProject)
By default, the project will come with two classes, which are
Program.cs and Form1.cs
The execution of Windows Application starts from the class 'Program',
which is 'static.' Under this class, we find the Main method creating
the object of 'Form' class which has to be executed.
Eg:
Application.Run(new Form1 ());

'Form1' is the file in which the class 'Form1' is defined inheriting form
predefined class 'Form' and this is the class that has to be executed.
Eg:
public partial class Form1:Form

Windows applications developed using Visual Studio has two places we


can work with
1) Design View
2) Code View
Here, Design View is the place, where we can design the application which is
accessible to both programmer and end user as well.
And Code View is the place, where we can write the code for execution of
application which is accessible only to the Programmers.

Properties

As we know that every control should have properties, methods and events.
To access properties and events, Visual Studio provides us property window,
which lists all properties corresponding to the control.
To open Properties window, select the control first and press F4, which will
display all properties which are available to that control. Please note that we
can change any property in the list like width, height, backcolor, etc and we
can see the change immediately.
Whenever we set value to any property of the control, Visual Studio will
internally write all the corresponding code referring to each property of the
control by assigning the values that we specified under property window. We
can easily view that code under a Method called "InitializeComponent",
which gets called from the constructor.

Note: We can view the code under "InitializeComponent" by going to


CodeView -> right click on the Method and select 'Form1.Designer.cs' and
here also we can find the same class 'Form1' which is partial as well.
Eg:
this.Text="First Form";
this.BackColor=Color.Blue;
this.Size = new Size(350,350);

Events
Events are time periods, which will tell when an action should be performed
i.e. when exactly we want to execute the code. Each and every control has a
number of events and each event occurs on a particular time period.
We can access the events of a control in property window. To view them in
property window, choose 'Events' option on top of the window.
We can write any code under an event by double clicking the required event,
which will take us to the Code View and provide a method in which we can
write the code.
In the project, which we have opened, go to Events, double click on 'Load
Event' then write the below code under 'Form1_Load' method generated in
CodeView.
MessageBox.Show("Welcome to Windows Applications");
Again, go to Design View -> select Events -> double click on 'Click' event ->
then write the below code under 'Form1_Click' method.
MessageBox.Show("You have clicked on Form");
Event Procedures
Event procedure is a special method that is available to Windows application,
which gets generated when we double click on an event in the property
window.
An Event Procedure is also called a method, but these are called by us
explicitly. They get bound with an event of control and execute whenever
the event occurs.
To execute this kind of methods, events will take help of a 'delegate.' So
whenever event occurs, it calls the delegate and delegate executes the
event procedure that is bound with the event.

Events and delegates are pre-defined. Here, events are defined under
controls and delegates are defined under System as well as
System.Windows.Forms namespaces.
Event procedures are user defined which are explicitly defined in our code
(Form class).
After defining the event to bind event delegate and event procedure, Visual
studio writes a statement binding all the three i.e. event, delegate and event
procedure as below.
Syntax:
<control>.<event> += new <delegate>(<event procedure>)
Eg:
this.Load += new EventHandler(Form1_Load);
this.Click += new EventHandler(Form1_Click);
Note: We can view the code under 'InitializeComponent' method
One delegate can be used by multiple events to execute event procedures,
which does not mean that same delegate will be used for all events.
Different events can use different delegates in order to execute event
procedures.
How to Define Event Procedures Manually
We can define an event procedure manually as below.
Syntax

[<modifiers>] void <Name> (object sender, Event Args e)


{
stmts
}

Event procedures are non-value returning methods.


The name of event procedure can be anything and it is purely userdefined.
Every event procedure takes two mandatory parameters which are
object sender and Event Args e

How to Set Properties and Define Event Procedure Manually


Write the below code in the notepad and execute.
using System;
using System.Drawing;
using System.Windows.Forms;
public class MyForm2:Forms;
{
public MyForm2()
{
InitializeComponent ();
}
private void InitializeComponent()
{
this.Text="MyForm";
this.BackColor=color.Pink;
this.Size=new size (350,350);
this.load +=new EventHandler (Test);
this.click +=new EventHndler (Test);
}
private void Test(object sender, EventArgs e)
{
static void Main()
{
MyForm2 f=new MyForm2 ();
Application.Run (f);
}
Note: Generally, the concept of event and event procedure is derived from
classical Visual Basic. In VB, one event procedure can be bound with only
one event of every control, whereas in .NET one event procedure can be
bound with multiple events of a single control as well as with multiple
controls also.

How to Add a New Form


To add a new form under a project, Open New Item window -> select
Windows Form which will add new form called Form2.cs.
In order to run the New Form, we need to open 'Programs.cs' class and
modify the value under 'Application.Run'" method as Form2 like below.
Application.Run (new Form2 ());
How to Bind an Event Procedure with Multiple Events of a Control in
Visual Studio
In the Form we added, define a load event by double clicking on Load Event
procedure. To bind the same event procedure to click event also, go to
events of our Form and under click event, select the event procedure Form2
load which was defined previously.
Now under the Event Procedure, write the below code.
MessageBox.Show(Bound with multiple Events of Control);
How to Place Controls on the Form
.NET provides us a number of controls in the form of classes where every
control acts like a class. All these controls are available under the ToolBox
which is present in the Left Hand Side. We can use any control by either
double clicking on it which will add the control to the form or select control in
ToolBox and click on the form which will add the control at desired location.
How to Bind an Event Procedure with Multiple Controls
Add a New Form in project and design it as below.

Define a 'Click' event procedure to Button and bind the event procedure with
remaining two TextBoxes and also the other Button.
Note: Check the Event Procedure that is bound with all five controls which
are two Buttons, two TextBoxes and a Form.
Now under the Event Procedure, write the below code.
if (sender.GetType().Name == "Button")
{
Button b = (Button)sender;
if (b.Name == "button1")
MessageBox.Show("Button1 clicked");
else if (b.Name == "button2")
MessageBox.Show("Button2 is clicked");
}
else if (sender.GetType().Name == "TextBox")
{
TextBox tb = sender as TextBox;
if (tb.Name == "textBox1")

MessageBox.Show("textbox1 is clicked");
else if (tb.Name == "textBox2")
MessageBox.Show("textbox2 is clicked");
}
else
MessageBox.Show("Form3 is clicked");

If an event procedure is bound with multiple controls, to recognize the


control that has raised the event, we can make use of the parameter
'sender' under the event procedure.
In above case, event procedure is bound with five controls. So in the
runtime the object of the control which has raised the event will be
sent to the event procedure which gets captured under the parameter
"sender" as below.

In above case, each control's object which is raising the event is sent
to the event procedure in runtime and captured under the parameter
"sender", where sender can hold any object in it because it is of type
object.

Because "sender" is holding objects of different control classes. We can


easily find out which control exactly raised the event by using 'GetType'
method of object class.
After using 'GetType' method to identify the type of control, now if we have
multiple controls of the same type to identify each and every control we
need to find out the name of the control. But the property name is available
under the child class using 'sender' we cannot identify the name. So first

'sender' needs to be converted into the appropriate control type by explicit


type casting as below.
if(sender.GetType().Name == "Button")
{
Button b= (Button) sender;
}
else if(sender.GetType().Name=="TextBox")
{
TextBox tb=sender as TextBox;
}
How does a Form gets created?
When a Form is added to the project internally below things happened
1) Creates a class inheriting from predefined class, Form so that new class
is also acts like Form.
Eg: public partial class Form1:Form
2) Sets same Initialization properties like Name, Text, etc under
InitializeComponent method.
Eg: this.Name="Form1";
this.Text="Form1";
How does a control gets placed on the Form?
When a controls placed on the Form, below things takes place.
1) Creates object of appropriate control class
Eg: Button button1 = new Button();
TextBox textBox1 = new TextBox();
2) Sets same Initialization properties like Name, Text, Size, Location, etc
Eg: button1.Name="button1";
button1.Text="button1";
button1.Location=new point(x,y);
button1.Size=new size(width,height);
3) Now the control gets added to form by calling control.AddMethod on
current form.
Eg: this.Controls.Add (button1);
Note:
All the above code will be generated by Visual Studio under
InitializeComponent Method.
In Windows application, code is of basically two types.
1) Designer Code
2) Business Logic

Designer Code: Code which is responsible for construction of the form is


known as Designer Code.
Business Logic: Code which is responsible for execution of the form is known
as Business Logic.
Designer Code is generated by Visual Studio under the Method
"InitializeComponent" and Business Logic is defined by programmers in the
form of 'Event Procedures".
Before .NET 2.0, Designer code and Business Logic were defined in a class
present under a file like below.
Before 2.0
---------Form1.cs
-------public class Form1:Form
{
-Designer Code
-Business Logic
}
But from .NET 2.0 with the introduction of partial classes, Designer code and
Business Logic are separated into two different files but of same class only
like below.
Form1.cs:
--------public partial class From1:From
{
-Business Logic
}
Form1.Designer.cs:
-----------------partial class Form1
{
-Designer Logic
}

Happy Learning.!!!!!

Windows Programming, CUI, GUI, Partial Classes, Properties, Events, Event


Procedures, Adding a New Form, Designer Code, Business Logic

Você também pode gostar