Professional Documents
Culture Documents
Attachment Decision Tree Regression Lyst6442
Attachment Decision Tree Regression Lyst6442
5 Window Forms
Agenda
1. Basic Controls
2. Panels and Layouts
3. Drawing and GDI Devices
4. MenuStrip, ToolStrip and ContextMenuStrip
5. Model and Modeless Dialog boxes
6. Multiple Document Interface (MDI)
7. Form Inheritance
8. Building Login Form
9. Working with Resource Files and Settings
10. Notify Icon Controls
11. Using Components like Timer, FileSystemWatcher, Process, BackgroundWorker
12. Drag and Drop
13. Working with Advanced controls like TreeView and ListView
1
Deccansoft Software Services - MS.NET 4.5 Window Forms
Window Forms
WinForms = Controls + Graphics
Used for Developing Rich GUI Application.
TextBox :
Properties: Text, PasswordChar, Multiline, Readonly, AutoCompleteMode, AutoCompleteSource,
AutoCompleteCustomSource
Events: KeyPress, KeyDown, TextChanged, Validating
AutoComplete Example
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim names() As String = New String() {"deccan", "deccansoft", "deccan chronical", "testing", "demo"}
Dim sc As AutoCompleteStringCollection = New AutoCompleteStringCollection
For Each name As String In names
sc.Add(name)
Next
txtDemo.AutoCompleteCustomSource = sc
txtDemo.AutoCompleteSource = AutoCompleteSource.CustomSource
End Sub
Code: 15.2 VB
AutoComplete Example
2
Deccansoft Software Services - MS.NET 4.5 Window Forms
3
Deccansoft Software Services - MS.NET 4.5 Window Forms
End If
End Sub
Code: 15.3 VB
Using KeyPress
private void txtDemo_KeyPress(object sender, KeyPressEventArgs e)
{
//MessageBox.Show(((int)e.KeyChar).ToString());
if ((int)e.KeyChar == 8) //for backspace
return;
if (e.KeyChar < '0' || e.KeyChar > '9') //If the Char is in range of 48 to 57.
e.Handled = true; //Don’t display the char in textbox.
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
MessageBox.Show("Control + A is Clicked");
}
//To validate the content of the textbox before the focus is lost from it:
private void txtDemo_Validating(object sender, CancelEventArgs e)
{
if (txtDemo.Text == "")
{
errorProvider1.SetError(txtDemo, "The value cannot be empty");
e.Cancel = true; //Doesn’t allow the textbox to lose focus.
}
else
errorProvider1.SetError(txtDemo, "");
}
Code: 15.3 C#
Button:
Button Properties: CausesValidation
Form Properties: AcceptButton, CancelButton (to be used in context of button)
CheckBox:
Properties: Text, Checked, ThreeState, CheckState (Checked/UnChecked/Intermediate)
Events: CheckedChanged.
4
Deccansoft Software Services - MS.NET 4.5 Window Forms
RadioButton:
To group we have to use a common container which can be either Form or Group Box or Panel.
ComboBox
Properties: Items, DropDownStyle (Simple/DropDownList/DropDown), Text, SelectedIndex, SelectedItem
Events: SelectedIndexChanged
Combobox Example
Class Student
Public Id As Integer
Combobox Example
class Student //Write outside the Form Class.
{
public int Id;
public string Name;
public Student(int id, string name)
{
5
Deccansoft Software Services - MS.NET 4.5 Window Forms
Id = id;
Name = name;
}
public override string ToString()
{
return Name;
}
}
private void DemoForm_Load(object sender, EventArgs e)
{
cmbStudent.Items.Add(new Student(1, "S1"));
cmbStudent.Items.Add(new Student(2, "S2"));
cmbStudent.Items.Add(new Student(3, "S3"));
cmbStudent.Items.Add(new Student(4, "S4"));
}
private void cmbStudent_SelectedIndexChanged (object sender, EventArgs e)
{
Student s = (Student)cmbStudent.SelectedItem;
MessageBox.Show(s.Id.ToString());
}
Code: 15.4 C#
Note: To a ComboBox any type of object can be added. The ToString() implementation of that objects will
be displayed as the Items text in the ComboBox.
DateTimePicker:
Properties: Value, MinDate, MaxDate, ShowCheckBox, Checked, ShowUpDown, Format,
CustomFormat (dd/MM/yyyy hh:mm:ss tt) – Only if Format = "Custom"
Events: ValueChanged
MonthCalander:
Properties: CalanderDimension.Width / Height, SelectionRange.Start /.End, ShowWeekNumbers
Events: DateChanged
MaskedTextBox:
Properties: Text, Mask, PromptChar
Containers
Panel
GroupBox
FlowLayoutPanel
TableLayoutPanel
TabControl
6
Deccansoft Software Services - MS.NET 4.5 Window Forms
SplitContainer
7
Deccansoft Software Services - MS.NET 4.5 Window Forms
8
Deccansoft Software Services - MS.NET 4.5 Window Forms
GDI Example:1
using System.Drawing.Drawing2D;
using System.Drawing;
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
int w, h;
w = this.ClientSize.Width;
h = this.ClientSize.Height;
Pen p = new Pen(Color.Red);
g.DrawArc(p, w / 2 - 50, h / 2 - 40, 100, 80, 0, 45);
p.Dispose();
p = new Pen(Color.Green);
9
Deccansoft Software Services - MS.NET 4.5 Window Forms
10
Deccansoft Software Services - MS.NET 4.5 Window Forms
Invalidate();
}
Code: 15.6 C#
Program to draw lines from MouseDown to MouseUp and also to save the same to file using Serialization
Graphics Form
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO
<Serializable()> _
Class Line
Dim From As Point
Dim TO2 As Point
End Class
Dim ptTo As Point
Dim lstLines As List(Of Line) = New List(Of Line)
Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
Dim g As Graphics = e.Graphics
Dim ptFrom As Point
For Each ln As Line In lstLines
g.DrawLine(Pens.Blue, ln.From, ln.TO2)
Next
End Sub
Private Sub Form1_MouseDown(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
If (e.Button = MouseButtons.Left) Then
ptFrom = e.Location
End If
End Sub
Private Sub Form1_MouseUp(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp
If (e.Button = MouseButtons.Left) Then
ptTo = e.Location
Dim ln As Line = New Line
ln.From = ptFrom
ln.To = ptTo
lstLines.Add(ln)
'Invalidate();
Dim g As Graphics = Me.CreateGraphics
g.DrawLine(Pens.Red, ptFrom, ptTo)
11
Deccansoft Software Services - MS.NET 4.5 Window Forms
g.Dispose()
End If
End Sub
Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnOpen.Click
Dim fs As FileStream = New FileStream("c:\\Deccansoft\\Lines.dat", FileMode.Open)
Dim bf As BinaryFormatter = New BinaryFormatter
lstLines = CType(bf.Deserialize(fs), List(Of Line))
fs.Close()
Invalidate()
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnSave.Click
Dim fs As FileStream = New FileStream("c:\Deccansoft\Lines.dat", FileMode.OpenOrCreate)
Dim bf As BinaryFormatter = New BinaryFormatter
bf.Serialize(fs, lstLines)
fs.Close()
End Sub
Code: 15.7 VB
Graphics Form
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
[Serializable()]
class Line
{
public Point From,To;
}
Point ptFrom, ptTo;
List<Line> lstLines = new List<Line>();
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
foreach(Line ln in lstLines)
g.DrawLine(Pens.Blue, ln.From, ln.To);
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
ptFrom = e.Location;
12
Deccansoft Software Services - MS.NET 4.5 Window Forms
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ptTo = e.Location;
Line ln = new Line();
ln.From = ptFrom;
ln.To = ptTo;
lstLines.Add(ln);
//Invalidate();
Graphics g = this.CreateGraphics();
g.DrawLine(Pens.Red, ptFrom, ptTo);
g.Dispose();
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream("c:\\Deccansoft\\Lines.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
lstLines = (List<Line>) bf.Deserialize(fs);
fs.Close();
Invalidate();
}
private void btnSave_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream("c:\\Deccansoft\\Lines.dat", FileMode.OpenOrCreate);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, lstLines);
fs.Close();
}
Code: 15.7 C#
13
Deccansoft Software Services - MS.NET 4.5 Window Forms
Code: 15.8 VB
Creating Image
Bitmap bmp = new Bitmap(200, 200); //The class Bitmap supports all the types of Images (bmp / gif / jpeg /
png …)
Graphics g = Graphics.FromImage(bmp);
g.FillEllipse(Brushes.Red, 0, 0, 200, 200);
g.DrawLine(Pens.Yellow, 0, 0, 200, 200);
g.DrawLine(Pens.Yellow, 0, 200, 200, 0);
bmp.Save("c:\\demo.gif", System.Drawing.Imaging.ImageFormat.Gif);
Code: 15.8 C#
14
Deccansoft Software Services - MS.NET 4.5 Window Forms
1. ToolboxIn Menus & Toolbars Tab Select Menu strip Drag and Drop it on the form.
2. Add the following menus:
Figure Rectangle / Ellipse / - (Separator) / Exit
3. Provide Shortcut Keys for Menu Items Rectangle (Ctrl + R) and Ellipse (Ctrl + E)
4. Handle Paint Event of the Form and Click Event handler of all the menu items
5. Add the following to the code view of the form (in form class).
15
Deccansoft Software Services - MS.NET 4.5 Window Forms
mnuEllipse.Click
fig = FigureType.Ellipse
Invalidate()
End Sub
Code: 15.9 VB
16
Deccansoft Software Services - MS.NET 4.5 Window Forms
fig = FigureType.Ellipse;
Invalidate();
}
Code: 15.9 C#
7. To Synchronize the MenuItems of the Form with the state of the application handle DropDown Opening
event of mnuFigure. Go to design view of the Form Select Figure Menu Properties windows Events
Tab Dropdown Opening.
Using DropDown Opening Event
Private Sub mnuFigure_DropDownOpening(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles mnuFigure.DropDownOpening
If (fig = FigureType.Rectangle) Then
mnuRectangle.Checked = True
mnuEllipse.Checked = False
Else
mnuEllipse.Checked = True
mnuRectangle.Checked = False
End If
End Sub
Code: 15.10 VB
17
Deccansoft Software Services - MS.NET 4.5 Window Forms
Code: 15.10 C#
8. Add to the Form a ContextMenuStrip control from Tool Box with Rectangle (cmnuRectangle) and Ellipse
(cmnuEllipse).
9. Select Rectangle goto Events Tab (Properties Window) For Click Event select already existing
mnuRectangle_Click method.
10. Select Ellipse go to Events Tab (Properties Window) For Click Event select already existing
mnuEllipse_Click method.
11. Select Form Properties ContextMenuStrip = “<Id of ContextMenuStrip>”
12. Run the form and test the above actions.
18
Deccansoft Software Services - MS.NET 4.5 Window Forms
a. Do the Form level Validations and if everything is OK execute the following line
b. Me.DialogResult = DialogResult.OK
7. Handle Cancel, Click Event
a. Me.DialogResult = DialogResult.Cancel
Note: If the DialogResult of the Modal DialogBox is set, The Dialog is immediately closed and the Dialog Result
set here becomes the return value of ShowDialog()_ in parent form
19
Deccansoft Software Services - MS.NET 4.5 Window Forms
set
{
txtY.Text = value.ToString();
}
}
public int X
{
get
{
return int.Parse(txtX.Text);
}
set
{
txtX.Text = value.ToString();
}
}
private void btnOK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
Code: 15.11 C#
In Form:
1. Add to the Form the following MENUITEMS
Edit Position / Color / Font / Text
2. Handle Click event of all the above menu items
MenuItem click event
Private Sub mnuPosition_Click(ByVal sender As Object, ByVal e As EventArgs) Handles mnuPosition.Click
Dim dlgPosition As PositionDialog = New PositionDialog
dlgPosition.X = Me.X
20
Deccansoft Software Services - MS.NET 4.5 Window Forms
dlgPosition.Y = Me.y
If (dlgPosition.ShowDialog = DialogResult.OK) Then
Me.X = dlgPosition.X
Me.y = dlgPosition.Y
Invalidate()
End If
End Sub
Code: 15.12 VB
Note:
ShowDialog shows the Dialog box in Modal form and this method returns only when the dialog box is Closed
(by settings is Dialog Result).
21
Deccansoft Software Services - MS.NET 4.5 Window Forms
Code for Color, Font and Text menu added to the form
private void colorToolStripMenuItem_Click(object sender, EventArgs e)
{
ColorDialog dlgColor = new ColorDialog();
dlgColor.Color = col;
if (dlgColor.ShowDialog() == DialogResult.OK)
{
col = dlgColor.Color;
Invalidate();
}
}
private void mnuFont_Click(object sender, EventArgs e)
22
Deccansoft Software Services - MS.NET 4.5 Window Forms
{
FontDialog dlgFont = new FontDialog();
dlgFont.Font = fnt;
if (dlgFont.ShowDialog() == DialogResult.OK)
{
fnt = dlgFont.Font;
Invalidate(); //Also modify the Paint Event handler to draw the text using new font.
}
}
private void mnuText_Click(object sender, EventArgs e)
{
OpenFileDialog dlgFile = new OpenFileDialog();
dlgFile.Filter = "Text Files(*.txt)|*.txt|All Files(*.*)|*.*";
if (dlgFile.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new System.IO.StreamReader(dlgFile.FileName);
txt = sr.ReadLine();
Invalidate();
}
}
Code: 15.13 C#
23
Deccansoft Software Services - MS.NET 4.5 Window Forms
Modeless Dialog
Step1: Before writing the following code, first add to the project a DemoDialog Form (Modeless). Goto DemoDialog
in handout.
Step5: Add to the Form a textbox (txtDemoInForm) and button (btnModelessDialog)
Step6: txtDemoInForm.Modifiers = “Public” (to access in modeless dialog, apply button click event handler)
Step7: Write the following code in the form
Modeless Dialog box
Private Sub btnModelessDialog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnModelessDialog.Click
If (dlgDemo Is Nothing) Then
dlgDemo = New DemoDialog
dlgDemo.DemoText = txtDemoInForm.Text
dlgDemo.Owner = Me
'Only then the dialog will always stay above the owner form
AddHandler dlgDemo.FormClosed, AddressOf Me.dlgDemo_FormClosed
dlgDemo.Show()
Else
dlgDemo.Activate()
End If
End Sub
Code: 15.14 VB
24
Deccansoft Software Services - MS.NET 4.5 Window Forms
If the Form (Dialog) is closed, the object referencing to the Form is not destroyed and the reference variable
“dlgDemo” would continue referencing to the object. Thus we can handle the “FormClosed” event and set the
reference to nothing as below.
25
Deccansoft Software Services - MS.NET 4.5 Window Forms
Code: 15.16 VB
26
Deccansoft Software Services - MS.NET 4.5 Window Forms
this.Close();
}
private void btnApply_Click(object sender, EventArgs e)
{
Form1 frmOwner = (Form1) this.Owner;
frmOwner.txtDemoInForm.Text = this.txtDemoInDialog.Text;
}
Code: 15.17 C#
27
Deccansoft Software Services - MS.NET 4.5 Window Forms
28
Deccansoft Software Services - MS.NET 4.5 Window Forms
29
Deccansoft Software Services - MS.NET 4.5 Window Forms
Step9: In MenuStrip Window Tile Horx / Tile Vert / Cascade / Arrange Icons
Step 9.1: MenuStrip Properties MdiWindowListItem = Window MenuItem (For showing the window list in window
menu)
Handling Toolstrip Items
Private Sub TileHorzToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.ToolStripItemClickedEventArgs) Handles TileHorzToolStripMenuItem.ItemClicked
Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub
Private Sub CascadeToolStripMenuItem _Click(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.ToolStripItemClickedEventArgs) Handles CascadeToolStripMenuItem.ItemClicked
Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub
Private Sub TileVertToolStripMenuItem _Click(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.ToolStripItemClickedEventArgs) Handles TileVertToolStripMenuItem.ItemClicked
Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub
Private Sub ArrangeIconsToolStripMenuItem _Click(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.ToolStripItemClickedEventArgs) Handles
ArrangeIconsToolStripMenuItem.ItemClicked
30
Deccansoft Software Services - MS.NET 4.5 Window Forms
Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub
Code: 15.23 VB
31
Deccansoft Software Services - MS.NET 4.5 Window Forms
The MenuItems in the MenuStrip of ActiveMdiChild are by default appended to the MenuStrip of MdiForm
To set the sequence of MenuItems on MdiParent and MdiChild For Every MenuItem set
MergeAction="Insert" and give appropriate MergeIndex based on positioning required
32
Deccansoft Software Services - MS.NET 4.5 Window Forms
Startup Class
33
Deccansoft Software Services - MS.NET 4.5 Window Forms
Note: To Copy Resource (e.g. .bmp / .xml file) to the Output Folder (folder of exe file):
Go to
newer.
34
Deccansoft Software Services - MS.NET 4.5 Window Forms
35
Deccansoft Software Services - MS.NET 4.5 Window Forms
Timer Control
Dim n As Integer
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
n = (n + 1)
label1.Text = n.ToString
End Sub
Private Sub btnStart_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnStart.Click
Timer1.Enabled = True
End Sub
Private Sub btnStop_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnStop.Click
Timer1.Enabled = False
End Sub
Code: 15.28 VB
Timer Control
int n;
private void timer1_Tick(object sender, EventArgs e)
{
n++;
label1.Text = n.ToString();
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
Code: 15.28 C#
NotifyIcon Control
36
Deccansoft Software Services - MS.NET 4.5 Window Forms
End Sub
Dim exits As Boolean = False
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
If exits Then
Return
End If
e.Cancel = True
Me.Visible = False
End Sub
Private Sub showToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles showToolStripMenuItem.Click
Me.Visible = True
End Sub
Private Sub exitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles exitToolStripMenuItem.Click
exits = True
Me.Close()
End Sub
Code: 15.5 VB
NotifyIcon Example
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Visible = true;
}
bool exit = false; //will be set to true of menu on notify icon is used.
private void DemoForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (exit)
return;
e.Cancel = true;
this.Visible = false;
}
private void showToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Visible = true;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
37
Deccansoft Software Services - MS.NET 4.5 Window Forms
exit = true;
this.Close();
}
Code: 15.5 C#
Summary:
38
Deccansoft Software Services - MS.NET 4.5 Window Forms
In this section we have studied Window Forms basic controls & associated events. The major controls, viz., Textbox,
Radio button, combo box, etc., GDI API, menus & dialog boxes, creating image programmatically and MDI.
39