1 Agenda: Understanding and Working with few important controls.

Developing Graphi cs / Drawing based application using GDI API Menus o MenuStrip o Synchronization of MenuItems with application. o Context Sensitive Menu Dialogboxes o Modal Dialogbox o Modeless Dialogbox Developing MDI Applications. To add Login facility to the a pplication. Working with Resource File. Working with Properties ? Settings. What is Form Inheritance. Working with Timer Component. NotifyIcon Control Deccansoft Software Services MS.NET Window Forms 2 Understanding and Working with few important controls. Control Properties: Dock, Anchor Label Properties: Text, Image, AutoSize, UseMnemonic PictureBox Properti es: Image, SizeMode (Normal / StretchImage / AutoSize / CenterImage / Zoom) Link Label Properties: Text, LinkVisited, LinkColor, VisitedLinkColor, ActiveLinkColo r, DisableLinkColor private void linkLabel1_LinkClicked(object sender, Link { Sy stem.Diagnostics.Process.Start("c:\demo.html"); } TextBox Properties: Text, Pas swordChar, Multiline, Readonly, AutoCompleteMode, AutoCompleteSource, AutoComple teCustomSource Events: KeyPress, KeyDown, TextChanged, Validating private void F orm1_Load(object sender, EventArgs e) { string[] names = { "deccan", "deccansoft ", "deccan chronical", "testing", "demo" }; AutoCompleteStringCollection sc = ne w AutoCompleteStringCollection(); foreach (string name in names) sc.Add(name); t xtDemo.AutoCompleteCustomSource = sc; txtDemo.AutoCompleteSource = AutoCompleteS ource.CustomSource; } In KeyDown we cannot distinguish upper and lower case char acters. KeyPress event fires only for keys with ASCII value where as KeyDown eve nt fires for all keys on the keyboard. private void txtDemo_KeyPress(object sender, KeyPressEventArgs e) { //MessageBox .Show(((int)e.KeyChar).ToString()); if ((int)e.KeyChar == 8) //for backspace ret urn; 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 text box before the focus is lost from it: private void txtDemo_Validating(object sen der, CancelEventArgs e) { if (txtDemo.Text == "") { errorProvider1.SetError(txtD emo, "The value cannot be empty"); e.Cancel = true; //Doesn t allow the textbox to loose focus. } else errorProvider1.SetError(txtDemo, ""); } Note: ErrorProvider is in Components Tab in Toolbox Button Properties: CausesValidation Form Proper ties: AcceptButton, CancelButton. Deccansoft Software Services MS.NET Window Forms 3 CheckBox: Properties: Text, Checked, ThreeState, CheckState (Checked/UnChecked/I ntermediate) Events: CheckedChanged. RadioButton: To group we have to use a comm on container which can be either Form or GroupBox or Panel. ComboBox Properties: Items, DropDownStyle (Simple/DropDownList/DropDown), Text, SelectedIndex, Selec tedItem Events: SelectedIndexChanged class Student //Write outside the Form Class. { public int Id; public string Nam e; public Student(int id, string name) { Id = id; Name = name; } public override string ToString() { return Name; } } private void DemoForm_Load(. . .) { cmbStudent.Items.Add(new Student(1,"S1")); c mbStudent.Items.Add(new Student(2,"S2")); cmbStudent.Items.Add(new Student(3,"S3 ")); cmbStudent.Items.Add(new Student(4,"S4")); } private void cmbStudent_Select edIndexChanged(. . .) { Student s = (Student)cmbStudent.SelectedItem; MessageBox .Show(s.Id.ToString()); } Note: To a ComboBox any type of object can be added. The ToString() implementati on of that objects will be displayed as the Items text in the ComboBox. DateTime Picker: 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, Selecti

g. br = new HatchBrush(HatchStyle. ln.Red).Red. //The class Bitmap supports all the types of Images (bmp / gif / jpeg / png ) Gra phics g = Graphics. h/2) .Blue).To = ptTo. 100. 50.Red.//. 70. } } private void btnOpen_Click(object sender.FromArgb(50. 0.Drawing. g.FillRectangle(br. } Deccansoft Software Services MS.TranslateTransform(w/2.Y = 100.Binary.InactiveCaption). 50).Gif). pts[2]. br.40.Red. EventArgs e) { FileStream fs = new FileStream("c:\Deccansoft\Lines.DrawLine(Pens. Graphics g = this.onRange. pts).FromKnownColor(KnownColor. Color.PageUnit = GraphicsUnit.IO.5F.50.DrawArc(p. pts[0]. Font f = new Font("Arial ". h. To). 0).Dispose().50 .FillEllipse(Brushes.45).ResetTransform (). 0. w = this. Brush br.F illEllipse(br.DrawLine(Pens.FillEllipse(br. g.Height. 240).Serialization. br = new SolidBrush(col).Loc ation.Formatter s.From. using System. 1. 200.Yellow.NET Window Forms 6 To Create an Image (bitmap) Programmatically Bitmap bmp = new Bitmap(200.To. 2). g.Button == MouseButtons.Drawing2D private void Form1_Paint(object sender. BinaryFormatter bf = new BinaryFormatter(). h = this. List<Line> lstLines = new Li st<Line>(). Mask. g. } private void btnSave_Click(object sender. br = new LinearGradientBrush(p1.End. g.Serialize(fs.DrawLine(p. 0.Drawing.D rawRectangle(p.CreateGraphics(). Color.Y = h / 2 + 50. FileMode. 200.50.DashedHorizonta l. 20. 200.From = ptFrom. g. g. } private void FigureForm_Resize(objec t sender. 0. h / 2 . g.DrawImage(img. w / 2 . FileMode. g. 200). foreach(Line ln in lstLines) g. 0). 30. 0).50.FromImage(bmp). ptFrom.X = w / 2.D rawLine(p. pts[1].Graphics.Y = h / 2 + 50. g.Open). Invalidate(). p2.ClientSize. int w. lstLines. 10) . Write the following in the Form [Serializable()] class Line { public Point From. fs. g. ln. Add the following menus: Figure ?Rectangle / Ellipse / . //To shift the origin g.ClientSi ze.Close().Red). System. .0.Deserialize( fs). ptTo). p1. 0. ptTo. p = new Pen(Color.Inch.Blue. Image img = new B itmap("C:\Windows\coffee bean. g. w. p1.O penOrCreate). PaintEventArgs e) { Graphics g = e.X = w / 2 . } Point ptFrom.Yellow. 200. 80. 100).ImageFormat. PaintEventArgs e) { Graphics g = e. 0. Toolbox?In Menus & Toolbars Tab ? Select Menu strip Drag and Drop it on the f orm.30. 255.Width. 80. EventArgs e) { Invalidate().Bold FontStyle. ShowWeekNumbers Events: DateChanged MaskedTextBox Propertie s: Text.DrawLine(Pens.dat". 127. / /Invalidate(). 200). Color col = Color. 200. g.Y = h / 2 . //Zoomin g Point p1 = new Point(). fs. lstLi nes).Location.X = w / 2 + 50. pts[2].But ton == MouseButtons. w. 100. 2).40.Red. 100.RotateTransform(-30). 10.Start /. pts[0].Yellow.Imaging. col = Color.Green). PromptChar Deccansoft Software Services MS.DrawRectangle(p. 80.NET Window Forms 5 Program to Draw lines From MouseDown to MouseUp and also to save the same to fil e using Serialization Graphics Form using System.ScaleTransform(2. g .FillEllipse(br. Color.NET Window Forms 7 Working with Menus and Dialogs 1. 0.Save("c:\demo. g. } private void Form1_MouseDown(object sender. bmp.X = 1 00.FromName("brow n"). g. p = new Pen(Color. private void Form1_Paint(object sender. lstLines = (List<Line>) bf.DrawPolygon(p. p2. p. g. g. bf.(Separator) / Exit .Add(ln). FontStyle. w / 2 . 200).dat". 24.Close(). g .DrawString("Hello".2F). Point[] pts = new Point[3]. //Brush is an abstract class.bmp").DrawLine(Pens.Dispose(). } Deccansoft Software Services MS. Event Args e) { FileStream fs = new FileStream("c:\Deccansoft\Lines. 2.X = 20. 0. ln. 30. Bin aryFormatter bf = new BinaryFormatter(). p2.Graphics.ResetTransform(). 10. Pen p = new Pen(Color. 80). Deccansoft Software Services MS. pts[1].NET Window Forms 4 Working with GDI using System.Runtime.Y = 30.Left) ptFrom = e. h).5F. 200. } private void Form1_MouseUp(obje ct sender. Line ln = new Line().Italic). 0. br = new Textur eBrush(img). MouseEventArgs e) { if (e. Color. 70).gif". Point p2 = new Point(). 0. ln. g. h / 2 . 12). g. 200.Left) { ptTo = e. 0. f. MouseEventArgs e) { if (e. h.

Filter = "Te . Run the Application.Black. if (fig = FigureType. DIALOG BOXES Two Types Of Dialogboxes 1.TranslateTransform(0. PaintEventArgs e) { Graphics g. FontDialog. } else { mnuEllipse. Comm on Dialogbox: ColorDialog.Red //Add this before coding for ColorDialog String tx t = "Hello" 'Add this before coding for FontDialog. Eve ntArgs e) { ColorDialog dlgColor = new ColorDialog(). } 6. EventArgs e) { fig = Fig ureType.Rectangle) { mnuRectangle. 100). Show/Hide. g = e. Select Ellipse goto Events Tab (Properties Window) ? For Click Event select already existing mnuEllipse_Click method. Handle Click event of all the above menu items private void mnuPosition_Click(.Bold). Run the form and test the above actions. Add to the Form a ContextMenuStrip control from ToolBox with Rectangle (cmnuR ectangle) and Ellipse (cmnuEllipse).Height). EventArgs e) { FontDialog dlgFont = new FontDialog(). //Also modify the Paint Event handler t o draw the text using new font. To Synchronize the MenuItems of the Form with the state of the application ha ndle DropDownOpening event of mnuFigure.DrawEllipse(p. . Add the following to the code view of the form (in form class).Font = fnt. private void Form1_Paint(object sender. x. Select Form ? Properties ? ContextMenuStrip = <Id of ContextMenuStrip> 12. . Color col = Color. EventArgs e) { this.) { PositionDialog dlgPosition = new Positio nDialog(). y. 100). Add to the Form the following MENUITEMS Edit ? Position / Color / Font / Text 3. Ev entArgs e) { OpenFileDialog dlgFile = new OpenFileDialog(). Invalidate(). Invalidate(). 200. dlgFile. 10. We have to write code for Opening and reading from file or writing to file using IO API. Provide ShortCutKeys for MenuItems ? Rectangle (Ctrl + R) and Ellipse (Ctrl + E) 4.Cl ose().Rectangle. Save FileDialog Note: OpenFileDialog and SaveFileDialog provides us the FileName with its Path. } private void mnuRectangle_Click(object sender. dlgColor. Invalidate(). } } 8.Checked = true.NET Window Forms 8 9. } } Note: ShowDialog shows the Dialogbox in Modal form and this meth od returns only when the dialogbox is Closed (by settings is DialogResult).OK) { col = dlgColor.D rawRectangle(p. g. y.OK) { this. private void colorToolStripMenuItem_Click(object sender.Graphics.Ellipse. Font fnt = new Font("Arial".Color. in t x.Checked = false. 2.//To Move o rigin after menustrip. mnuEllipse. Walkthrough BEFORE THE FOLLOWING CODE IS WRITTEN DIALOG CLASS SHOULD BE CREATED.ShowDialog() == DialogResult . OpenFileDialog. Model: Unless it is disposed we cannot work with the parent form.X = this. Handle Paint Event of the Form and Click Event handler of all the menu items 5.Checked = false.Y = dlgPosition. Brushes.X. dlgFont.Y. GOTO Position Dialog (Page 7) 2. Select Rectangle goto Events Tab (Properties Window) ? For Click Event select already existing mnuRectangle_Click method. Invalidate(). enum FigureType { Rectangle.Font. Menu Synchronization Enable/Disable. if (dlgPosition. Change the Text o f MenuItems Based on Application State 7.Y.DrawSt ring(txt.Y = this.Rectangle. dlgPosition. Pen p = New Pen(col). Deccansoft Software Services MS.X. else g. fnt. 14.OK) { fnt = dlgFont. EventArgs e) { if (fig == FigureType. 100.ShowDialog() == DialogResult. 11. y. } private void mnuExit_Click(object sender. 100. Check/UnCheck. 200). msMain. } private void mnuEllipse_Click(object sender. this. FontStyle. EventArgs e) { fig = FigureType. dlgPosition. In validate(). FolderBrowserDialog.Rectangle) g. Modeless: It always remains on top of the owner form but while it is open we can also work with the owner form. 1. } } private void mnuText_Click(object sender. private void mnuFigure_DropDownOpening(object sender.ShowD ialog() == DialogResult. if (dlgFont. if ( dlgColor. Goto design view of the Form ? Select F igure Menu ? Properties windows ? Events Tab ? DropDownOpening . Ellipse } FigureType fig = FigureType.3.//Add this line after adding code for Fo nt Dialogbox.Color = col. x.Checked = true. g.X = dlgPosition. } } private void mnuFont_Click(object sender. mnuRectangle.

} } 6. EventArgs e) { if (dlgDemo == null) { dlgDemo = new DemoDialog().Close(). } set { txtY.txt) *. Invalidate(). } Note: If the DialogResult of the ModalDialogBox is set. Add Properties to the DialogBox class so that the Control Properties are avai lable to the form where the Dialog is used. frmOwner. For Ex: X and Y property which encap sulate the textboxes on the dialog. . Click Event private void btnOK_Click(object sender.Close().OK. Click Event private void btnCancel_Click(object sender.xt Files(*. Event Args e) { this. EventArgs e) { btnApply_Cli ck(sender. EventArgs e ) { Step 8: Form1 frmOwner = (Form1) this. } private void btnApply_Click(object sender.Text). Set the following Form Properties: a. txt = sr.Text = t his.NET Window Forms 9 { System. private void btnOK_Click(object sender. dlgDemo.ShowDialog() == DialogRes ult.txtDemoInForm.DialogResult = D ialogResult.txt All Files(*. e).txtDemoInDialog.cs) 2. FormBorderStyle FixedDialog b.NET Window Forms 10 MODELESS DIALOG.Text). give them proper name and set corre ct TabOrder (Select Form ? View Menu ? TabOrder). Steps for Creating Modal DialogBox: 1. Step1: Add a new Form to the Dialog and name it as DemoDialog S tep2: Design the dialog as shown in the adjacent figure and Id of TextBox is (tx tDemoInDialog) Step3: Add the Property DemoText to the dialog class. MinimizeBox false c.ToSt ring().Text = value. Design the Dialog Place all the controls. Handle Cancel. EventArgs e) { //Do the Form level Valid ations and if everything is OK execute the following line this.Text. this. Apply and Can cel buttons. if (dlgFile. Show the Dialog using ShowDialog() Method 4.FileName). Set the Dialog Properties 3. Step5: Add to the Form a textbox (txtDemoInForm) and button (btnModelessDialog) Step6: txtDemoInForm. apply button click event handler) Step7: Write the following cod e in the form DemoDialog dlgDemo.ToString(). } } Step4: Handle click event of OK. StartPosition CenterParent 3.Text. Create the instance of the Dialog Class.*) *.DialogResult = Di alogResult. Add a new Windows Form to the project (PositionDialog.OK) Steps for showing the Dialog 1. } Note: After Step4 btnApply_Click will be Empty. } 7. } private void btnCancel_Click(object sender.StreamReader(dlgFile. 4. EventArgs e) { this.*".StreamReader sr = new System.Text = value. MaximiseBox false d. private void btnModelessDialog_Click(object se nder.IO.ReadLine(). Write the Validations for the controls on the Dialog 5. public int Y { get { return int. } } Position Dialog Add the following to the Posi tionDialog Class. Add the following to the Form.Parse(txtX. public string DemoText { get { return txtDemoInDialog.IO. If OK is Pressed use the dialog properties Deccansoft Software Services MS.Modifiers = Public (to access in m odeless dialog.Parse(txtY. } set { txtX. Th e Dialog is immediately closed and the DialogResult set here becomes the return value of ShowDialog()_ in parent form Deccansoft Software Services MS.Cancel. ShowInTaskBar false e. Handle OK. } set { txtDemoInDialog. 2.Text = value.Owner. } } public int X { get { return int.

Enabled = false. .) Me.To Confirm before the Form is Closed ? Handle FormClosing Event private v oid MdMainForm_FormClosing(object sender. //Form will not closed.resx and Imag es.YesNo)./ Exit Step5: To allowing mutiple instance of Form1 private void mnuShowForm1 _Click(object sender. } Step9: In MenuStrip Window ? Tile Horx / Tile Vert / Cascade / Arrange Icons Step 9. EventArgs e) { if (frmForm2 == null) { frmForm2 = new Form2().Cancel = true. FormClosingEventArgs e) { DialogResult res = MessageBox.LayoutMdi(MdiLayout. EventArgs e) { Form1 frmForm1 = new Form1(). } Step7: To Close All Children of an MDI Form Add Menu File ? .No) e..Cascade ) End Sub Private Sub TileVertToolStripMenuItem_Click(. Work ing with Resource Files To the Project add Resource Files (Strings. } Step8: To Synchronize the MenuItem with respect to active mdi child. EventArgs e) { if (this.ShowDialog() == DialogResult. .TileHo rizontal) End Sub Private Sub CascadeToolStripMenuItem_Click(.LayoutMdi(MdiLayout.MdiCh ildren) frm. Add a New WindowsForm (Mdi MainForm) and set its IsMDIContainer=True Step4: Add Menu: File ? Form1/ Form2 / .Text.Cancel.Run(new MainForm()). / Close All private void closeAllToolS tripMenuItem_Click(object sender. } Startup Class static class Program { public static void Main() { LoginDialog dlg Login = new LoginDialog().OK) Applica tion. frmForm1. frmForm1.Activate().resx add Key-Value pairs K1 = This is K1 K2 = This is K2 To Images. EventArgs e) { this. Step2: Add to it a Windows Form (Form2) Step3.) Me. Thus w e can handle the FormClosed event and set the reference to nothing as below. //Only then the dialog will always stay above the owner form dlgDemo.LayoutMdi(MdiLayout. } private void btnCancel_Click(objec t sender. dlgDemo.DialogResult = DialogResult. } else frmForm2.Show().Ar rangeIcons) End Sub Step10. dlgDemo.Owner = this.FormClosed += new FormClosedEventHandler(frmForm2_Form Closed). "Close". FormClosedEventArgs e) { dlgDemo = null.FormClosed += new FormClosedEventHandl er(dlgDemo_FormClosed). .Show("Invalid Username or Password").Close(). .xml file) to t he Output Folder (folder of exe file): Select the file in Solution Explorer ? Go to Properties ? Set Copy to Output Directory = Copy always / Copy if newer. else Messa geBox. if (r es == DialogResult. . } } Note: To Copy Resource (eg: . FormClosedEventArgs e) { frmForm2 = null.NET Window Forms 11 Multiple Document Interface (MDI) Step1: Create a New WindowsFormsApplication Pr oject.resx add and Images to it with some name. private void mnuShowForm2_Click(object s ender. if (dlgLogin. } Step6: To allow single instance of Form2 at any given instance of time Form2 frmForm2. EventArgs e) { foreach (Form frm in this.Show(). .Show("Are you sure?". frmForm2.Activate(). frmForm2. When the Project is Build Two C .DemoText = txtDemoInForm. } Note: If th e Form (Dialog) is closed.OK.M diParent = this.ActiveMdiChil d is Form2) activateForForm2ToolStripMenuItem.) Me. the object referencing to the Form is not destroyed a nd the reference variable dlgDemo would continue referencing to the object.MdiP arent = this. frmForm2. . .TileVe rtical) End Sub Private Sub ArrangeIconsToolStripMenuItem_Click(. else activateForFo rm2ToolStripMenuItem. In MenuStrip Add Testing ? ActiveForForm2 private void testingToolSt ripMenuItem_DropDownOpening(object sender.LayoutMdi(MdiLayout.DialogResult = DialogResult.Text == txtPassword. } Deccansoft Software Services MS. } Deccansoft Software Services MS. void dlgDemo_FormClosed(object sender. EventArgs e) { if (txtUs ername.Text) this.1 MenuStrip Properties ? MdiWindowLi stItem = Window MenuItem (For showing the window list in window menu) Private Sub TileHorzToolStripMenuItem_Click(.Show(). MessageBoxButtons.NET Window Forms 12 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 ba sed on positioning required Adding Login Facility to the application Login Dialog private void btnLogin_Click(object sender.) Me.resx) To Strings. } else dlgDemo. } void frmForm2_FormClosed (object sender.bmp / .Enabled = true.

settings Add ? Name= Left . EventA rgs e) { timer1. EventArgs e) { n++. } private void btnStop_Click(object sender.Save().Left. } NotifyIcon Control To the Form add NotifyIc on control and ContextMenuStrip. Even tArgs e) { timer1. label1. we don t have to copy the images separately. //will be set to true of menu on notifyicon is used.Text = n. Type= int .Properties . Value= 0 To Save the Position of the Form when it is closed so hat the same position can be restored when it is opened next time: Handle Form ? Load event private void MiscForm_Load(object sender. Scope= User . } private void sho wToolStripMenuItem_Click(object sender. <ProjectName>.Left = this. Thus when the application is deployed on the client machine.Visible = true.Cancel = true.Enabled = false. private void timer1_Tick(object sender.Close().Default. EventArgs e) { this. FormClosingEventArgs e) { if (exit) return.Properties.Default.Top.Top = <ProjectName>. Working with Properties ? Settings Goto Solution Explorer ? Under Project ? Prop erties ? Settings. To the ContextMenuStrip add two Items (Show and Exit) Set Icon and ContextMenuStrip properties of NofifyIcon and handle MouseDo ubleClick event.Default. } Handle Form ? FormClosing Event private void MiscFo rm_FormClosing(object sender.Visible = true. private void notifyIcon1_MouseDoubleClick(object sender. MouseEventArgs e) { thi s.Settings.Default.Enabled = true.Settings.Top.Default. } . } bool exit=false.Visible = false. e.Left = <ProjectName>.To p = this. } Deccansoft Software Services MS.Proper ties. } pr ivate void exitToolStripMenuItem_Click(object sender. private void DemoForm_FormClosing(object sender. If the Project the Content of the Image files is included in the Exe/Dll. Scope= User .Settings. <ProjectName>. EventArgs e) { exit = true . } private void btnStart_Click(object sender. Value= 0 Add ? Na Type= int .Settings.lass (Strings and Images) are automatically created based on the content in the resource file. this. All the keys added to the resource files become Static/Shared mem bers in these classes. this. this.Left.Properties.NET Window Forms 13 Timer Control int n.Properties. FormClosingEventArgs e) { <ProjectName>. EventArgs e) { this.ToString().Settings.