Вы находитесь на странице: 1из 6

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

onRange.Start /.End, ShowWeekNumbers Events: DateChanged MaskedTextBox Propertie s: Text, Mask, PromptChar Deccansoft Software Services MS.NET Window Forms 4 Working with GDI using System.Drawing.Drawing2D private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; int w, h; w = this.ClientSi ze.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); g.D rawRectangle(p, w / 2 - 50, h / 2 - 40, 100, 80); g.DrawLine(p, 0, 0, w, h); g.D rawLine(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("brow n");//.FromKnownColor(KnownColor.InactiveCaption); br = new SolidBrush(col); g.F illEllipse(br, 10, 10, 100, 100); br = new HatchBrush(HatchStyle.DashedHorizonta l, Color.Yellow, Color.Red); g.FillEllipse(br,30, 30, 50, 50); Image img = new B itmap("C:\\Windows\\coffee bean.bmp"); g.DrawImage(img, 200, 0); br = new Textur eBrush(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); //Zoomin g Point p1 = new Point(); Point p2 = new Point(); p1.X = 20; p1.Y = 30; p2.X = 1 00; 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(objec t sender, EventArgs e) { Invalidate(); } Deccansoft Software Services MS.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.Runtime.Serialization.Formatter s.Binary; using System.IO; Write the following in the Form [Serializable()] class Line { public Point From,To; } Point ptFrom, ptTo; List<Line> lstLines = new Li st<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.But ton == MouseButtons.Left) ptFrom = e.Location; } private void Form1_MouseUp(obje ct sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ptTo = e.Loc ation; 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); Bin aryFormatter bf = new BinaryFormatter(); lstLines = (List<Line>) bf.Deserialize( fs); fs.Close(); Invalidate(); } private void btnSave_Click(object sender, Event Args e) { FileStream fs = new FileStream("c:\\Deccansoft\\Lines.dat", FileMode.O penOrCreate); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, lstLi nes); fs.Close(); } Deccansoft Software Services MS.NET Window Forms 6 To Create an Image (bitmap) Programmatically Bitmap bmp = new Bitmap(200, 200); //The class Bitmap supports all the types of Images (bmp / gif / jpeg / png ) Gra phics 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); Deccansoft Software Services MS.NET Window Forms 7 Working with Menus and Dialogs 1. Toolbox?In Menus & Toolbars Tab ? Select Menu strip Drag and Drop it on the f orm. 2. Add the following menus: Figure ?Rectangle / Ellipse / - (Separator) / Exit

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

xt Files(*.txt) *.txt All Files(*.*) *.*"; if (dlgFile.ShowDialog() == DialogRes ult.OK) 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 Deccansoft Software Services MS.NET Window Forms 9 { System.IO.StreamReader sr = new System.IO.StreamReader(dlgFile.FileName); txt = sr.ReadLine(); Invalidate(); } } Position Dialog Add the following to the Posi tionDialog Class. Steps for Creating Modal DialogBox: 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 corre ct TabOrder (Select Form ? View Menu ? TabOrder). 4. Write the Validations for the controls on the Dialog 5. Add Properties to the DialogBox class so that the Control Properties are avai lable to the form where the Dialog is used. For Ex: X and Y property which encap sulate the textboxes on the dialog. public int Y { get { return int.Parse(txtY.Text); } set { txtY.Text = value.ToSt ring(); } } public int X { get { return int.Parse(txtX.Text); } set { txtX.Text = value.ToString(); } } 6. Handle OK, Click Event private void btnOK_Click(object sender, EventArgs e) { //Do the Form level Valid ations and if everything is OK execute the following line this.DialogResult = Di alogResult.OK; } 7. Handle Cancel, Click Event private void btnCancel_Click(object sender, EventArgs e) { this.DialogResult = D ialogResult.Cancel; } Note: If the DialogResult of the ModalDialogBox is set, Th e Dialog is immediately closed and the DialogResult set here becomes the return value of ShowDialog()_ in parent form Deccansoft Software Services MS.NET Window Forms 10 MODELESS DIALOG. 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. public string DemoText { get { return txtDemoInDialog.Text; } set { txtDemoInDialog.Text = value; } } Step4: Handle click event of OK, Apply and Can cel buttons. private void btnOK_Click(object sender, EventArgs e) { btnApply_Cli ck(sender, e); this.Close(); } private void btnCancel_Click(object sender, Event Args e) { this.Close(); } private void btnApply_Click(object sender, EventArgs e ) { Step 8: Form1 frmOwner = (Form1) this.Owner; frmOwner.txtDemoInForm.Text = t his.txtDemoInDialog.Text; } Note: After Step4 btnApply_Click will be Empty. Add the following to the Form. Step5: Add to the Form a textbox (txtDemoInForm) and button (btnModelessDialog) Step6: txtDemoInForm.Modifiers = Public (to access in m odeless dialog, apply button click event handler) Step7: Write the following cod e in the form DemoDialog dlgDemo; private void btnModelessDialog_Click(object se nder, 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 FormClosedEventHandl er(dlgDemo_FormClosed); dlgDemo.Show(); } else dlgDemo.Activate(); } Note: If th e Form (Dialog) is closed, the object referencing to the Form is not destroyed a nd the reference variable dlgDemo would continue referencing to the object. Thus w e can handle the FormClosed event and set the reference to nothing as below. void dlgDemo_FormClosed(object sender, FormClosedEventArgs e) { dlgDemo = null; } Deccansoft Software Services MS.NET Window Forms 11 Multiple Document Interface (MDI) Step1: Create a New WindowsFormsApplication Pr oject. Step2: Add to it a Windows Form (Form2) Step3. Add a New WindowsForm (Mdi MainForm) and set its IsMDIContainer=True Step4: Add Menu: File ? Form1/ Form2 / - / Exit Step5: To allowing mutiple instance of Form1 private void mnuShowForm1 _Click(object sender, EventArgs e) { Form1 frmForm1 = new Form1(); frmForm1.MdiP arent = this; frmForm1.Show(); } Step6: To allow single instance of Form2 at any given instance of time Form2 frmForm2; private void mnuShowForm2_Click(object s ender, EventArgs e) { if (frmForm2 == null) { frmForm2 = new Form2(); frmForm2.M diParent = this; frmForm2.FormClosed += new FormClosedEventHandler(frmForm2_Form Closed); frmForm2.Show(); } else frmForm2.Activate(); } void frmForm2_FormClosed (object sender, FormClosedEventArgs e) { frmForm2 = null; } Step7: To Close All Children of an MDI Form Add Menu File ? .. / Close All private void closeAllToolS tripMenuItem_Click(object sender, EventArgs e) { foreach (Form frm in this.MdiCh ildren) frm.Close(); } Step8: To Synchronize the MenuItem with respect to active mdi child. In MenuStrip Add Testing ? ActiveForForm2 private void testingToolSt ripMenuItem_DropDownOpening(object sender, EventArgs e) { if (this.ActiveMdiChil d is Form2) activateForForm2ToolStripMenuItem.Enabled = true; else activateForFo rm2ToolStripMenuItem.Enabled = false; } Step9: In MenuStrip Window ? Tile Horx / Tile Vert / Cascade / Arrange Icons Step 9.1 MenuStrip Properties ? MdiWindowLi stItem = Window MenuItem (For showing the window list in window menu) Private Sub TileHorzToolStripMenuItem_Click(. . .) Me.LayoutMdi(MdiLayout.TileHo rizontal) End Sub Private Sub CascadeToolStripMenuItem_Click(. . .) Me.LayoutMdi(MdiLayout.Cascade ) End Sub Private Sub TileVertToolStripMenuItem_Click(. . .) Me.LayoutMdi(MdiLayout.TileVe rtical) End Sub Private Sub ArrangeIconsToolStripMenuItem_Click(. . .) Me.LayoutMdi(MdiLayout.Ar rangeIcons) End Sub Step10.To Confirm before the Form is Closed ? Handle FormClosing Event private v oid MdMainForm_FormClosing(object sender, FormClosingEventArgs e) { DialogResult res = MessageBox.Show("Are you sure?", "Close", MessageBoxButtons.YesNo); if (r es == DialogResult.No) e.Cancel = true; //Form will not closed. } Deccansoft Software Services MS.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, EventArgs e) { if (txtUs ername.Text == txtPassword.Text) this.DialogResult = DialogResult.OK; else Messa geBox.Show("Invalid Username or Password"); } private void btnCancel_Click(objec t sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; } Startup Class static class Program { public static void Main() { LoginDialog dlg Login = new LoginDialog(); if (dlgLogin.ShowDialog() == DialogResult.OK) Applica tion.Run(new MainForm()); } } Note: To Copy Resource (eg: .bmp / .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. Work ing with Resource Files To the Project add Resource Files (Strings.resx and Imag es.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 C

lass (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 mem bers 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 ? Prop erties ? Settings.settings Add ? Name= Left , Type= int , Scope= User , Value= 0 Add ? Na Type= int , Scope= User , 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, EventArgs e) { this.Left = <ProjectName>.Properties.Settings.Default.Left; this.Top = <ProjectName>.Proper ties.Settings.Default.Top; } Handle Form ? FormClosing Event private void MiscFo rm_FormClosing(object sender, FormClosingEventArgs e) { <ProjectName>.Properties .Settings.Default.Left = this.Left; <ProjectName>.Properties.Settings.Default.To p = this.Top; <ProjectName>.Properties.Settings.Default.Save(); } Deccansoft Software Services MS.NET Window Forms 13 Timer Control int n; private void timer1_Tick(object sender, EventArgs e) { n++; label1.Text = n.ToString(); } private void btnStart_Click(object sender, EventA rgs e) { timer1.Enabled = true; } private void btnStop_Click(object sender, Even tArgs e) { timer1.Enabled = false; } NotifyIcon Control To the Form add NotifyIc on control and ContextMenuStrip. To the ContextMenuStrip add two Items (Show and Exit) Set Icon and ContextMenuStrip properties of NofifyIcon and handle MouseDo ubleClick event. private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { thi s.Visible = true; } bool exit=false; //will be set to true of menu on notifyicon is used. private void DemoForm_FormClosing(object sender, FormClosingEventArgs e) { if (exit) return; e.Cancel = true; this.Visible = false; } private void sho wToolStripMenuItem_Click(object sender, EventArgs e) { this.Visible = true; } pr ivate void exitToolStripMenuItem_Click(object sender, EventArgs e) { exit = true ; this.Close(); }