WinForms: GUI Programming in .NET Goal “.NET supports two types of form-based apps, WinForms and WebForms. WinForms are the traditional, desktop GUI apps. The great news is that Visual Studio .NET enables quick, dragand-drop construction of form-based applications…” • • • • UCN 2012 Event-drevet, code-behind programmering Visual Studio .NET WinForms Controls 2 Part 1 • Event-drevet, code-behind programing… UCN 2012 3 Event-driven applications • The idea is very simple: – “user actions” becomes “events” – events is transferred one by one to the application, which processes the event in a eventhandler GUI App – This is how most gui’s are made… UCN 2012 4 Eksamples on GUI-baserede events • • • • • • • • • UCN 2012 Mouse move Mouse click Mouse double-click Key press Button click Menu selection Change in focus Window activation etc. 5 Code-behind • Events are handled by methods (eventhandlers). These eventhandlers is placed “behind” the visiable GUI – In MS-terms known as "code-behind" – Our job is to program there methods… UCN 2012 6 Call-backs • Events is a call from an object back to us… • How is the connection made? – Visual Studio establish the connection via autogenerated code. UCN 2012 7 Part 2 • Visual Studio .NET… UCN 2012 8 Visual Studio .NET (VS.NET) • One IDE used for all forms of .NET development – From classlibraries over form-based apps to web services – You can use C#, VB, C++, J#, etc. UCN 2012 9 Basis operation • Visual Studio operates in 1 of 3 ways: 1) design 2) run design 3) break run break • See VS title bar if you are in doubt… UCN 2012 10 Example: a windows-application • GUI apps based on forms and controls… – one form represents a window – One form has 0 or more controls – One control interacts with the user • Let us implement a GUI app in a number of steps… UCN 2012 11 Step 1 • Make a new project of type “Windows Application” – VS. will automatically make a form… UCN 2012 12 Step 2 — GUI design • Find the controls from the toolbox… – Place the mouse over the toolbox to see controls – drag-and-drop on the form – Place and size your controls UCN 2012 13 GUI design … • A simple calculator: • Place and configure controls – Click to chose – set properties viathe Properties-window UCN 2012 14 Step 3 — codedesign • Implement the forms “Code behind”… • Dobbelt-clik on the control you want to implement – the eventhandler is generated UCN 2012 15 Step 4 — run mode • Run! UCN 2012 16 Break mode? • Is started in this appI for example by typing something wrong… UCN 2012 17 Work with Visual Studio • In Visual Studio we work with source files, projects & solutions • Source files holds code – extension .cs, .vb, etc. • A project represents 1 assembly – Used by VS to keep track of source files – all source files must be written in the same – language – extension .csproj, .vbproj, etc. • Solution (*.sln) files keeps track of projects – So you can work on more than one project UCN 2012 18 Part 3 • WinForms… UCN 2012 19 WinForms • Another name for traditional, Windowslike GUI-applications – Unlike WebForms, which is web-based • Is implementer via FCL – Portable to any .NET platform UCN 2012 20 Abstraction • FCL works as an abstraction – parts WinForm app from the underlaying platform object instance of FCL class System.Windows.Forms.Form CLR Windows OS UCN 2012 21 Form properties • Form properties controls the forms visual apperance: – – – – – – – – – – Form1 form; AutoScroll form = new Form1(); form.WindowState = FormWindowState.Maximized; BackgroundImage form.Show(); ControlBox FormBorderStyle (sizable?) Icon Location Size StartPosition Text (fx window's caption) WindowState (minimized, maximized, normal) UCN 2012 22 Form methods • Actions which can be executed on a form: – – – – – UCN 2012 Activate: Close: Hide: Refresh: Show: form.Hide(); . . . form.Show(); give this form focus close & free ressourcer save, but keep resources for later use. redraw make the form visible on screen & activate 23 Form events • Events you can react on: – find the propertieswindow – dubbleclik on the event-name – – – – – – UCN 2012 Load: Closing: Closed: Resize: Click: KeyPress: just before the form is shown for the first time when the form is closing (cancel is possible) when the form can be closed in a secure way when the user changes the form-size when the user clicks on the forms background when the user press some button on the keyboard while the form has focus 24 Example • ASK THE USER BEFORE A FORM IS CLOSED: private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { DialogResult r; r = MessageBox.Show("Do you really want to close?", "MyApp", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (r == DialogResult.No) e.Cancel = true; } UCN 2012 25 Part 4 • Controls… UCN 2012 26 Controls • Userinterfaceobjecter på formen: – – – – – – – – UCN 2012 labels buttons text boxes menus list & combo boxes option buttons check boxes etc. 27 Abstraction • Some forms, are controls based on classes in FCL: – System.Windows.Forms.Label – System.Windows.Forms.TextBox – System.Windows.Forms.Button – etc. object object • Controls are objecter of these classes object object object UCN 2012 object 28 Who makes all these objecter? • UCN 2012 Who is responsible for creating control-objects?-generated by Visual Studio – After the form-object is created the control-objects are made… 29 Naming conventions • Set named the names of your controls via Name property • The Microsoft Naming Convention: – cmdOK referes to a command-button – lstNames refers to a List Box Control – txtFirstName refers to a Textbox Control UCN 2012 30 Labels • Used for static text – Used as labels on other things in the form – Or for visualising read-only results • Interesting properties: – Text: what the user sees – Font: how the user sees UCN 2012 31 Command-knapper • For clicking and thereby initiate some action • Interesting properties: – Text: buttontext – Font: How the button is shown – Enabled: possible to click? – AcceptButton: Click on ENTER – CancelButton: Click on ESC • Interesting events: – Click: When the button is pushed UCN 2012 32 Text boxes • Most normal control! – Show test – data from for example databases • Lots of features… UCN 2012 33 Text box properties • Basic properties: – Text: what is in the box (string) – Modified: is the text modified by the user? (boolean) – ReadOnly: if the user should not be able to modify • Multi-line text boxes? – MultiLine: True makes multiple lines possible – Lines: array of strings, one for each line in the textbox – ScrollBars: none, horizontal, vertical or both horiz. & vert. – AcceptsReturn & AcceptsTab: sould the user be able to use tabulator and return UCN 2012 34 Text box methods • Interesting methoder: – Clear: – Cut, Copy, Paste: – Undo: – Select, SelectAll: UCN 2012 remove content interaction with clipboard undo last change in textbox chose some of the content 35 Text box events • Intereresting events: – Enter, Leave: – KeyPress: – KeyDown, KeyUp: – TextChanged: appears when focus changes appears when some ascii button is activated appears with keyboard combinations appears when text changes – Validating and Validated • Validating makes it possible to reject invalid input UCN 2012 36 Example: input invalidation • Text boxe often demands validation – .NET offers the Validating event – Triged when a box looses focus cmdOk.CausesValidation = True cmdCancel.CausesValidation = False private void txtName_Validating(object sender, System.ComponentModel.CancelEventArgs e) { if (this.textBox1.Text.Trim() == "") { // invalid input! MessageBox.Show("Please enter name or id..."); e.Cancel = true; // cancel returns focus back to text box } } UCN 2012 37 Caveats • The Validating event has some “points"… • Error: - If the cancel button is triggeret by ESC, it is still validated – If the user click x to close form, it is still validated • If the vox can have focus: – What if the user trigger OK via enter(default)?? – What if th user clicks OK before it gets focus? UCN 2012 38 Work-arounds… • Hide the box • Don’t set the box’ CancelButton property • Asure validation in OK button: private void cmdOK_Click(object sender, System.EventArgs e) { foreach (Control c in this.Controls) if (c is TextBox) { // check for valid input... c.Focus(); // give control focus, then validate if (!this.Validate()) return; } } UCN 2012 39 Radio buttons and Check boxes • Makes it possible for the user to choose one or more options • Radio buttons: – The user can only choose one(mutually-exclusive) • Check boxes: – The user can choose more than one (independent) • Properties & events: – Checked: – CheckedChanged UCN 2012 True if choosen, False if not appears when "Checked“ is changed 40 Group boxes • Visual grupping of controls • Make iteration over the groupmembers • possible… foreach (RadioButton rb in this.groupBox1.Controls) if (rb.Checked) MessageBox.Show(rb.Name); UCN 2012 41 List Boxes • Good for visualising lists of data – Lists of strings – Lists of object (list box will call ToString()) Customer[] customers; . . // create & fill array with objects... . // display customers in list box foreach (Customer c in customers) this.listBox1.Items.Add(c); // display name of selected customer (if any) Customer c; c = (Customer) this.listBox1.SelectedItem; if (c == null) return; else MessageBox.Show(c.Name); UCN 2012 42 Warnings 1. Don’t write code where the order of events matters… – The orders is never garantied – Every event is independent from others 2. Some kode trigger events behimd the code… – A natural sideeffect of event-drevet programmering this.textBox1.Text = "new value" UCN 2012 // triggers TextChanged 43 Only a small part of it all… • Menuer, dialoger, toolbars, etc. • Tousend of other controls – .NET and ActiveX – Rightclick onToolbox – "Customize Toolbox" UCN 2012 44 Summing up • Event-driven programming is very intuitive with GUI apps • Forms are the first step in GUI design – every form represents a window on the screen – Construction of GUI with drag-and-drop • The user interacts primary with the forms control-objekter – labels, text boxes, buttons, etc. – GUI programming is control programming!!! UCN 2012 45 References • Books: – S. Lippman, "C# Primer" – R. Grimes, "Developing Applications with Visual Studio .NET" • De bedste bøger om GUI er pt VB-baserede: – J. Savage, "The VB.NET Coach" (introductory) – F. Balena, "Programming Microsoft VB .NET (Core Reference)" (broad coverage, intermediate level) UCN 2012 46