Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

Deccansoft Software Services - MS.NET 4.

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.

Important Properties of Controls:


 Control Properties: Dock, Anchor
 Label Properties: Text, Image, AutoSize, UseMnemonic
 PictureBox Properties: Image, SizeMode (Normal / StretchImage / AutoSize / CenterImage / Zoom)
 LinkLabel Properties: Text, LinkVisited, LinkColor, VisitedLinkColor, ActiveLinkColor, DisableLinkColor
Using Link Label
Private Sub linkLabel1_Click(. . .) Handles linkLabel1.Click
System.Diagnostics.Process.Start("c:\demo.html")
End Sub
Code: 15.1 VB

Using Link Label


private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("c:\\demo.html");
}
Code: 15.1 C#

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

private void Form1_Load(object sender, EventArgs e)


{
string[] names = { "deccan", "deccansoft", "deccan chronical", "testing", "demo" };
AutoCompleteStringCollection sc = new AutoCompleteStringCollection();
foreach (string name in names)
sc.Add(name);
txtDemo.AutoCompleteCustomSource = sc;
txtDemo.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
Code: 15.2 C#
Note:
 In KeyDown we cannot distinguish upper and lower case characters.
 KeyPress event fires only for keys with ASCII value where as KeyDown event fires for all keys on the keyboard.
Using KeyPress
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
'MessageBox.Show(((int)e.KeyChar).ToString());
If (CType(e.KeyChar, Integer) = 8) Then
Return
End If
If ((e.KeyChar < Microsoft.VisualBasic.ChrW(48)) _
OrElse (e.KeyChar > Microsoft.VisualBasic.ChrW(57))) Then
e.Handled = True
End If
'Don_t display the char in textbox.
End Sub
Private Sub TextBox1_KeyDown(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If (e.Control AndAlso (e.KeyCode = Keys.A)) Then
MessageBox.Show("Control + A is Clicked")
End If
End Sub
Private Sub TextBox1_Validating(ByVal sender As System.Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If (txtDemo.Text = "") Then
errorProvider1.SetError(txtDemo, "The value cannot be empty")
e.Cancel = True
'Doesn_t allow the textbox to lose focus.
Else
errorProvider1.SetError(txtDemo, "")

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#

Note: ErrorProvider is in ComponentsTab in Toolbox

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

Public Name As String


Public Sub New(ByVal id As Integer, ByVal name As String)
MyBase.New()
id = id
name = name
End Sub
Public Overrides Function ToString() As String
Return Name
End Function
End Class
Private Sub DemoForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
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"));
End Sub
Private Sub cmbStudent_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmbStudent.SelectedIndexChanged
Dim s As Student = CType(cmbStudent.SelectedItem, Student)
MessageBox.Show(s.Id.ToString)
End Sub
Code: 15.4 VB

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

Working with GDI Objects and Graphics


Graphical objects: Line, Rectangle, Ellipse, Polygon, Arc …
GDI Objects: Pen, Brush, Font, Image
Brush and Image are abstract classes
GDI Example:1
Imports System.Drawing.Drawing2D
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles MyBase.Paint
Dim g As Graphics = e.Graphics
Dim h As Integer
Dim w As Integer
w = Me.ClientSize.Width
h = Me.ClientSize.Height
Dim p As Pen = New Pen(Color.Red)
g.DrawArc(p, ((w / 2) - 50), ((h / 2) - 40), 100, 80, 0, 45)
p.Dispose()
p = New Pen(Color.Green)
g.DrawRectangle(p, ((w / 2) - 50), ((h / 2) - 40), 100, 80)
g.DrawLine(p, 0, 0, w, h)
g.DrawLine(p, 0, h, w, 0)
Dim pts() As Point = New Point((3) - 1) {}
pts(0).X = (w / 2)
pts(0).Y = ((h / 2) + 50)
pts(1).X = ((w / 2) + 50)
pts(1).Y = ((h / 2) + 50)
pts(2).X = ((w / 2) - 50)
pts(2).Y = ((h / 2) + 50)
g.DrawPolygon(p, pts)
Dim br As Brush
'Brush is an abstract class.
Dim col As Color = Color.FromArgb(50, 255, 127, 12)
col = Color.FromName("brown")
'.FromKnownColor(KnownColor.InactiveCaption);
br = New SolidBrush(col)
g.FillEllipse(br, 10, 10, 100, 100)
br = New HatchBrush(HatchStyle.DashedHorizontal, Color.Yellow, Color.Red)
g.FillEllipse(br, 30, 30, 50, 50)
Dim img As Image = New Bitmap("C:\\Windows\\coffee bean.bmp")
g.DrawImage(img, 200, 0)
br = New TextureBrush(img)
g.FillEllipse(br, 80, 80, 200, 240)

8
Deccansoft Software Services - MS.NET 4.5 Window Forms

g.TranslateTransform((w / 2), (h / 2))


'To shift the origin
g.RotateTransform(-30)
g.ScaleTransform(2, 2)
'Zooming
Dim p1 As Point = New Point
Dim p2 As Point = New Point
p1.X = 20
p1.Y = 30
p2.X = 100
p2.Y = 100
br = New LinearGradientBrush(p1, p2, Color.Red, Color.Blue)
g.FillRectangle(br, 20, 30, 70, 70)
g.ResetTransform()
Dim f As Font = New Font("Arial", 24, (FontStyle.Bold Or FontStyle.Italic))
g.DrawString("Hello", f, br, 200, 10)
g.PageUnit = GraphicsUnit.Inch
p = New Pen(Color.Red, 0.2!)
g.ResetTransform()
g.DrawRectangle(p, 0.5!, 0.5!, 1, 2)
End Sub
Private Sub Form1_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Resize
Invalidate()
End Sub
Code: 15.6 VB

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

g.DrawRectangle(p, w / 2 - 50, h / 2 - 40, 100, 80);


g.DrawLine(p, 0, 0, w, h);
g.DrawLine(p, 0, h, w, 0);
Point[] pts = new Point[3];
pts[0].X = w / 2;
pts[0].Y = h / 2 - 50;
pts[1].X = w / 2 + 50;
pts[1].Y = h / 2 + 50;
pts[2].X = w / 2 - 50;
pts[2].Y = h / 2 + 50;
g.DrawPolygon(p, pts);
Brush br; //Brush is an abstract class.
Color col = Color.FromArgb(50, 255, 127, 12);
col = Color.FromName("brown");//.FromKnownColor(KnownColor.InactiveCaption);
br = new SolidBrush(col);
g.FillEllipse(br, 10, 10, 100, 100);
br = new HatchBrush(HatchStyle.DashedHorizontal, Color.Yellow, Color.Red);
g.FillEllipse(br, 30, 30, 50, 50);
Image img = new Bitmap("C:\\Windows\\coffee bean.bmp");
g.DrawImage(img, 200, 0);
br = new TextureBrush(img);
g.FillEllipse(br, 80, 80, 200, 240);
g.TranslateTransform(w / 2, h / 2); //To shift the origin
g.RotateTransform(-30);
g.ScaleTransform(2, 2); //Zooming
Point p1 = new Point();
Point p2 = new Point();
p1.X = 20; p1.Y = 30; p2.X = 100; p2.Y = 100;
br = new LinearGradientBrush(p1, p2, Color.Red, Color.Blue); ;
g.FillRectangle(br, 20, 30, 70, 70);
g.ResetTransform();
Font f = new Font("Arial", 24, FontStyle.Bold | FontStyle.Italic);
g.DrawString("Hello", f, br, 200, 10);
g.PageUnit = GraphicsUnit.Inch;
p = new Pen(Color.Red, 0.2F);
g.ResetTransform();
g.DrawRectangle(p, 0.5F, 0.5F, 1, 2);
}
private void FigureForm_Resize(object sender, EventArgs e)
{

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#

To Create an Image Programmatically:


Creating Image
Dim bmp As Bitmap = New Bitmap(200, 200) '//The class Bitmap supports all the types of Images (bmp / gif /
jpeg / png …)
Dim g As Graphics = Graphics.FromImage(bmp)
g.FillEllipse(Brushes.Red, 0, 0, 200, 200)
g.DrawLine(Pens.Yellow, 0, 0, 200, 200)

13
Deccansoft Software Services - MS.NET 4.5 Window Forms

g.DrawLine(Pens.Yellow, 0, 200, 200, 0)


bmp.Save("c:\demo.gif", System.Drawing.Imaging.ImageFormat.Gif)

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

Working with Menus and Dialogs

1. ToolboxIn 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).

Working with Menus and Dialogs


Enum FigureType
Rectangle
Ellipse
End Enum
Dim fig As FigureType = FigureType.Rectangle
Dim y As Integer
Dim col As Color = Color.Red
Dim txt As String = "Hello"
Dim fnt As Font = New Font("Arial", 14, FontStyle.Bold)
Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
Dim g As Graphics
g = e.Graphics
g.TranslateTransform(0, msMain.Height)
Dim p As Pen = New
If .DrawRectangle(p, x, y, 100, 100) Then
elseg.DrawEllipse(p, x, y, 100, 100)
g.DrawString(txt, fnt, Brushes.Black, 200, 200)
'Add this line after adding code for Font Dialogbox.
End Sub
Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
mnuExit.Click
Me.Close()
End Sub
Private Sub mnuRectangle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
mnuRectangle.Click
fig = FigureType.Rectangle
Invalidate()
End Sub
Private Sub mnuEllipse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles

15
Deccansoft Software Services - MS.NET 4.5 Window Forms

mnuEllipse.Click
fig = FigureType.Ellipse
Invalidate()
End Sub
Code: 15.9 VB

Working with Menus and Dialogs


enum FigureType
{
Rectangle,
Ellipse
}
FigureType fig = FigureType.Rectangle;
int x, y;
Color col = Color.Red; //Add this before coding for Color Dialog
String txt = "Hello"; //Add this before coding for Font Dialog.
Font fnt = new Font("Arial", 14, FontStyle.Bold);
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g;
g = e.Graphics;
g.TranslateTransform(0, msMain.Height);//To Move origin after menu strip.
Pen p = New Pen(col);
if (fig = FigureType.Rectangle)
g.DrawRectangle(p, x, y, 100, 100);
else
g.DrawEllipse(p, x, y, 100, 100);
g.DrawString(txt, fnt, Brushes.Black, 200, 200);//Add this line after adding code for Font Dialogbox.
}
private void mnuExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void mnuRectangle_Click(object sender, EventArgs e)
{
fig = FigureType.Rectangle;
Invalidate();
}
private void mnuEllipse_Click(object sender, EventArgs e)
{

16
Deccansoft Software Services - MS.NET 4.5 Window Forms

fig = FigureType.Ellipse;
Invalidate();
}
Code: 15.9 C#

6. Run the Application.


Note: Menu Synchronization – Enable/Disable, Show/Hide, Check/UnCheck, Change the Text of MenuItems
– Based on Application State.

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

Using DropDown Opening Event


private void mnuFigure_DropDownOpening(object sender, EventArgs e)
{
if (fig == FigureType.Rectangle)
{
mnuRectangle.Checked = true;
mnuEllipse.Checked = false;
}
else
{
mnuEllipse.Checked = true;
mnuRectangle.Checked = false;
}
}

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.

Working with Dialog Boxes


Two Types of Dialog boxes:
1. Model: Unless it is disposed we cannot work with the parent form.
2. Modeless: It always remains on top of the owner form but while it is open we can also work with the owner
form.
Generic Steps for Creating Any Modal Dialog Box:
1. Add a new Windows Form to the project (PositionDialog.cs)
2. Set the following Form Properties:
a. FormBorderStyle – FixedDialog
b. MinimizeBox – false
c. MaximiseBox – false
d. ShowInTaskBar – false
e. StartPosition – CenterParent
3. Design the Dialog – Place all the controls, give them proper Name and set correct Tab Order (Select Form ->View
Menu -> Tab Order).

4. Write the Validations for the controls on the Dialog


5. Add Properties to the Dialog Box class so that the Control Properties are available to the form where the Dialog is
used.
For Ex: X and Y property which encapsulate the textboxes on the dialog.
6. Handle OK, Click Event

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

Using Modal Dialog boxes


Public Property Y As Integer
Get
Return Integer.Parse(txtY.Text)
End Get
Set(ByVal value As Integer)
txtY.Text = value.ToString
End Set
End Property
Public Property X As Integer
Get
Return Integer.Parse(txtX.Text)
End Get
Set(ByVal value As Integer)
txtX.Text = value.ToString
End Set
End Property
Private Sub btnOK_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnOK.Click
Me.DialogResult = DialogResult.OK
End Sub
Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCancel.Click
Me.DialogResult = DialogResult.Cancel
End Sub
Code: 15.11 VB

Using Modal Dialog boxes


public int Y
{
get
{
return int.Parse(txtY.Text);
}

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#

General Steps for showing the Dialog:


1. Create the instance of the Dialog Class.
2. Set the Dialog Properties
3. Show the Dialog using ShowDialog() Method
4. If OK is pressed use the dialog properties

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

MenuItem click event


private void mnuPosition_Click(object sender, EventArgs e)
{
PositionDialog dlgPosition = new PositionDialog();
dlgPosition.X = this.X;
dlgPosition.Y = this.Y;
if (dlgPosition.ShowDialog() == DialogResult.OK)
{
this.X = dlgPosition.X;
this.Y = dlgPosition.Y;
Invalidate();
}
}
Code: 15.12 C#

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).

Common Dialog Boxes


1. ColorDialog
2. FontDialog
3. FolderBrowserDialog
4. OpenFileDialog
5. SaveFileDialog
Code for Color, Font and Text menu added to the form
Private Sub colorToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles colorToolStripMenuItem.Click
Dim dlgPosition As PositionDialog = New PositionDialog
dlgPosition.X = Me.X
dlgPosition.Y = Me.y

21
Deccansoft Software Services - MS.NET 4.5 Window Forms

If (dlgPosition.ShowDialog = DialogResult.OK) Then


Me.X = dlgPosition.X
Me.y = dlgPosition.Y
Invalidate()
End If
End Sub
Private Sub mnuFont_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
mnuFont.Click
Dim dlgFont As FontDialog = New FontDialog
dlgFont.Font = fnt
If (dlgFont.ShowDialog = DialogResult.OK) Then
fnt = dlgFont.Font
Invalidate()
'Also modify the Paint Event handler to draw the text using new font.
End If
End Sub
Private Sub mnuText_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
mnuText.Click
Dim dlgFile As OpenFileDialog = New OpenFileDialog
dlgFile.Filter = "Text Files(*.txt)|*.txt|All Files(*.*)|*.*"
If (dlgFile.ShowDialog = DialogResult.OK) Then
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(dlgFile.FileName)
txt = sr.ReadLine
Invalidate()
End If
End Sub
Code: 15.13 VB

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

Modeless Dialog box


DemoDialog dlgDemo;
private void btnModelessDialog_Click(object sender, EventArgs e)
{
if (dlgDemo == null)
{
dlgDemo = new DemoDialog();
dlgDemo.DemoText = txtDemoInForm.Text;
dlgDemo.Owner = this; //Only then the dialog will always stay above the owner form
dlgDemo.FormClosed += new FormClosedEventHandler(dlgDemo_FormClosed);
dlgDemo.Show();
}
else
dlgDemo.Activate();
}
Code: 15.14 C#

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.

Form closed event


Private Sub dlgDemo_FormClosed(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
dlgDemo = Nothing
End Sub
Code: 15.15 VB

Form closed event


void dlgDemo_FormClosed(object sender, FormClosedEventArgs e)
{
dlgDemo = null;
}
Code: 15.15 C#

Steps to Add DemoDialog to Project (Modeless Dialog)


Step1: Add a new Form to the Dialog and name it as Demo Dialog
Step2: Design the dialog as shown in the adjacent figure and Id of Text Box is (txtDemoInDialog)
Step3: Add the Property “DemoText” to the dialog class.

Demo Text Property


Public Property DemoText As String
Get
Return txtDemoInDialog.Text
End Get
Set(ByVal value As String)
txtDemoInDialog.Text = value
End Set
End Property

25
Deccansoft Software Services - MS.NET 4.5 Window Forms

Code: 15.16 VB

Demo Text Property


public string DemoText
{
get
{
return txtDemoInDialog.Text;
}
set
{
txtDemoInDialog.Text = value;
}
}
Code: 15.16 C#

Step4: Handle click event of OK, Apply and Cancel buttons.


Handle click event of OK, Apply and Cancel buttons.
Private Sub btnOK_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnOK.Click
btnApply_Click(sender, e)
Me.Close()
End Sub
Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCancel.Click
Me.Close()
End Sub
Private Sub btnApply_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnApply.Click
Dim frmOwner As Form1 = CType(Me.Owner, Form1)
frmOwner.txtDemoInForm.Text = Me.txtDemoInDialog.Text
End Sub
Code: 15.17 VB

Handle click event of OK, Apply and Cancel buttons.


private void btnOK_Click(object sender, EventArgs e)
{
btnApply_Click(sender, e);
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{

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#

Note: After Step4 btnApply_Click will be Empty.

27
Deccansoft Software Services - MS.NET 4.5 Window Forms

Multiple Document Interface (MDI)


Step1: Create a New WindowsFormsApplication Project.
Step2: Add to it a Windows Form (Form2)
Step3. Add a New WindowsForm (MdiMainForm) and set its IsMDIContainer=True
Step4: Add Menu: File  Form1/ Form2 / - / Exit
Step5: To allowing mutiple instance of Form1
Add the following code to the form
Private Sub mnuShowForm1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles
mnuShowForm1.Click
Dim frmForm1 As Form1 = New Form1
frmForm1.MdiParent = Me
frmForm1.Show()
End Sub
Code: 15.19 VB

Add the following code to the form


private void mnuShowForm1_Click(object sender, EventArgs e)
{
Form1 frmForm1 = new Form1();
frmForm1.MdiParent = this;
frmForm1.Show();
}
Code: 15.19 C#

Step6: To allow single instance of Form2 at any given instance of time


Add the following code to the form
Private Sub mnuShowForm2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles
mnuShowForm2.Click
If (frmForm2 Is Nothing) Then
frmForm2 = New Form2
frmForm2.MdiParent = Me
AddHandler frmForm2.FormClosed, AddressOf Me.frmForm2_FormClosed
frmForm2.Show()
Else
frmForm2.Activate()
End If
End Sub
Code: 15.20 VB

28
Deccansoft Software Services - MS.NET 4.5 Window Forms

Add the following code to the form


Form2 frmForm2;
private void mnuShowForm2_Click(object sender, EventArgs e)
{
if (frmForm2 == null)
{
frmForm2 = new Form2();
frmForm2.MdiParent = this;
frmForm2.FormClosed += new FormClosedEventHandler(frmForm2_FormClosed);
frmForm2.Show();
}
else
frmForm2.Activate();
}
void frmForm2_FormClosed(object sender, FormClosedEventArgs e)
{
frmForm2 = null;
}
Code: 15.20 C#

Step7: Add Menu File  ….. / Close All


Close All Children of an MDI Form
Private Sub closeAllToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles
closeAllToolStripMenuItem.Click
For Each frm As Form In Me.MdiChildren
frm.Close()
Next
End Sub
Code: 15.21 VB

Close All Children of an MDI Form


private void closeAllToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (Form frm in this.MdiChildren)
frm.Close();
}
Code: 15.21 C#

Step8: In MenuStrip Add Testing  ActiveForForm2

29
Deccansoft Software Services - MS.NET 4.5 Window Forms

To Synchronize the MenuItem with respect to active mdi child.


Private Sub testingToolStripMenuItem_DropDownOpening(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles testingToolStripMenuItem.DropDownOpening
If (TypeOf Me.ActiveMdiChild Is Form2) Then
activateForForm2ToolStripMenuItem.Enabled = True
Else
activateForForm2ToolStripMenuItem.Enabled = False
End If
End Sub
Code: 15.22 VB

To Synchronize the MenuItem with respect to active mdi child.


private void testingToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
{
if (this.ActiveMdiChild is Form2)
activateForForm2ToolStripMenuItem.Enabled = true;
else
activateForForm2ToolStripMenuItem.Enabled = false;
}
Code: 15.22 C#

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

Handling Toolstrip Items


private void CascadeToolStripMenuItem(object sender, ToolStripItemClickedEventArgs e)
{
this.LayoutMdi(MdiLayout.TileHorizontal);
}
private void TileVertToolStripMenuItem(object sender, ToolStripItemClickedEventArgs e)
{
this.LayoutMdi(MdiLayout.TileHorizontal);
}
private void ArrangeIconsToolStripMenuItem(object sender, ToolStripItemClickedEventArgs e)
{
this.LayoutMdi(MdiLayout.TileHorizontal);
}
Code: 15.23 C#

Step10: To Confirm before the Form is Closed  Handle FormClosing Event


Handling Form closing event
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
Dim res As DialogResult = MessageBox.Show("Are you sure?", "Close", MessageBoxButtons.YesNo)
If (res = DialogResult.No) Then
e.Cancel = True
End If
'Form will not closed.
End Sub
Code: 15.24 VB

Handling Form closing event


private void MdMainForm_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult res = MessageBox.Show("Are you sure?", "Close", MessageBoxButtons.YesNo);
if (res == DialogResult.No)
e.Cancel = true; //Form will not closed.
}
Code: 15.24 C#

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

Adding Login Facility to the application


Login Dialog

Working with Login


Private Sub btnLogin_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnLogin.Click
If (txtUsername.Text = txtPassword.Text) Then
Me.DialogResult = DialogResult.OK
Else
MessageBox.Show("Invalid Username or Password")
End If
End Sub
Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCancel.Click
Me.DialogResult = DialogResult.Cancel
End Sub
Code: 15.25 VB

Working with Login


private void btnLogin_Click(object sender, EventArgs e)
{
if (txtUsername.Text == txtPassword.Text)
this.DialogResult = DialogResult.OK;
else
MessageBox.Show("Invalid Username or Password");
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
Code: 15.25 C#

Startup Class

33
Deccansoft Software Services - MS.NET 4.5 Window Forms

Setting a startup class


Class Program
Public Shared Sub Main()
Dim dlgLogin As LoginDialog = New LoginDialog
If (dlgLogin.ShowDialog = DialogResult.OK) Then
Application.Run(New MainForm)
End If
End Sub
End Class
Code: 15.26 VB

Setting a startup class


static class Program
{
public static void Main()
{
LoginDialog dlgLogin = new LoginDialog();
if (dlgLogin.ShowDialog() == DialogResult.OK)
Application.Run(new MainForm());
}
}
Code: 15.26 C#

Note: To Copy Resource (e.g. .bmp / .xml file) to the Output Folder (folder of exe file):
Go to
newer.

Working with Resource Files


To the Project add Resource Files (Strings.resx and Images.resx)
To Strings.resx add Key-Value pairs
K1 = This is K1
K2 = This is K2
To Images.resx add and Images to it with some name.
 When the Project is Build Two Class (Strings and Images) are automatically created based on the content in
the resource file.
 All the keys added to the resource files become Static/Shared members in these classes.
 If the Project the Content of the Image files is included in the Exe/Dll. Thus when the application is deployed
on the client machine, we don’t have to copy the images separately.
Working with Properties  Settings
Goto Solution Explorer  Under Project  Properties  Settings.settings

34
Deccansoft Software Services - MS.NET 4.5 Window Forms

Add  Name=“Left”, Type= “int”, Scope=“User”, Value=“0”


Add  Name=“Top” Type= “int”, Scope=“User”, Value=“0”
To Save the Position of the Form when it is closed so that the same position can be restored when it is opened
next time:
Handle Form  Load event
Handling Form load event for initial position
Private Sub MiscForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
thisProjectNameProperties.Settings.Default.Left()
thisProjectNameProperties.Settings.Default.Top()
End Sub
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
ProjectName.Properties.Settings.Default.Left = Me.Left
ProjectName.Properties.Settings.Default.Top = Me.Top
ProjectName.Properties.Settings.Default.Save
End Sub
Code: 15.27 VB

Handling Form load event for initial position


private void MiscForm_Load(object sender, EventArgs e)
{
this.Left = <ProjectName>.Properties.Settings.Default.Left;
this.Top = <ProjectName>.Properties.Settings.Default.Top;
}
//Handle Form -> Closing Event
private void MiscForm_FormClosing(object sender, FormClosingEventArgs e)
{
<ProjectName>.Properties.Settings.Default.Left = this.Left;
<ProjectName>.Properties.Settings.Default.Top = this.Top;
<ProjectName>.Properties.Settings.Default.Save();
}
Code: 15.27 C#

Form Inheritance Demo


We can reuse the design of the form by inheriting a new form from an existing form class.

Timer Control Demo

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

 To the Form add NotifyIcon control and ContextMenuStrip.


 To the ContextMenuStrip add two Items (Show and Exit)
 Set Icon and ContextMenuStrip properties of NofifyIcon and handle MouseDoubleClick event.
NotifyIcon Example
Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
Me.Visible = True

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#

Drag and Drop


Example 1: To copy Image from Panel1 to Panel2:
1. panel2.AllowDrop = true;
2. Handle the MouseDown event of panel1 and DragEnter and DragDrop events of panel2
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
DoDragDrop(panel1.BackgroundImage, DragDropEffects.Copy);
}
private void panel2_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(Bitmap)))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void panel2_DragDrop(object sender, DragEventArgs e)
{
panel2.BackgroundImage = (Bitmap)e.Data.GetData(typeof(Bitmap));
}

Example2: To drag and drop files in Listbox:


1. listBox1.AllowDrop = true;
2. Handle DropEnter and DragDrop event of ListBox
private void listBox1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.All;
}
private void listBox1_DragDrop(object sender, DragEventArgs e)
{
string[] FileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach (string File in FileList)
listBox1.Items.Add(File);
}

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

You might also like