1 / 46

WinForms: GUI Programming in .NET

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, drag-and-drop construction of form-based applications…”

sauda
Download Presentation

WinForms: GUI Programming in .NET

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. WinForms: GUI Programming in .NET

  2. 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, drag-and-drop construction of form-based applications…” • Event-drevet, code-behind programmering • Visual Studio .NET • WinForms • Controls

  3. Part 1 • Event-drevet, code-behind programing…

  4. 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 • This is how most gui’s are made… GUI App

  5. Eksamples on GUI-baserede events • Mouse move • Mouse click • Mouse double-click • Key press • Button click • Menu selection • Change in focus • Window activation • etc.

  6. 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…

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

  8. Part 2 • Visual Studio .NET…

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

  10. design run break Basis operation • Visual Studio operates in 1 of 3 ways: • design • run • break • See VS title bar if you are in doubt…

  11. 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…

  12. Step 1 • Make a new project of type “Windows Application” • VS. will automatically make a form…

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

  14. GUI design … • A simple calculator: • Place and configure controls • Click to chose • set properties viathe Properties-window

  15. Step 3 — codedesign • Implement the forms “Code behind”… • Dobbelt-clik on the control you want to implement – the eventhandler is generated

  16. Step 4 — run mode • Run!

  17. Break mode? • Is started in this appI for example by typing something wrong…

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

  19. Part 3 • WinForms…

  20. WinForms • Another name for traditional, Windowslike GUI-applications • Unlike WebForms, which is web-based • Is implementer via FCL • Portable to any .NET platform

  21. object Abstraction • FCL works as an abstraction • parts WinForm app from the underlaying platform instance of FCL class System.Windows.Forms.Form CLR Windows OS

  22. Form properties • Form properties controls the forms visual apperance: • AutoScroll • BackgroundImage • ControlBox • FormBorderStyle (sizable?) • Icon • Location • Size • StartPosition • Text (fx window's caption) • WindowState (minimized, maximized, normal) Form1 form; form = new Form1(); form.WindowState = FormWindowState.Maximized; form.Show();

  23. Form methods form.Hide(); . . . form.Show(); • Actions which can be executed on a form: • Activate: give this form focus • Close: close & free ressourcer • Hide: save, but keep resources for later use. • Refresh: redraw • Show: make the form visible on screen & activate

  24. Form events • Events you can react on: • find the propertieswindow • dubbleclik on the event-name • Load: just before the form is shown for the first time • Closing: when the form is closing (cancel is possible) • Closed: when the form can be closed in a secure way • Resize: when the user changes the form-size • Click: when the user clicks on the forms background • KeyPress: when the user press some button on the keyboard while the form has focus

  25. 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; }

  26. Part 4 • Controls…

  27. Controls • Userinterfaceobjecter på formen: • labels • buttons • text boxes • menus • list & combo boxes • option buttons • check boxes • etc.

  28. object object object object object object Abstraction • Some forms, are controls based on classes in FCL: • System.Windows.Forms.Label • System.Windows.Forms.TextBox • System.Windows.Forms.Button • etc. • Controls are objecter of these classes

  29. Who makes all these objecter? • Who is responsible for creating control-objects?-generated by Visual Studio • After the form-object is created the control-objects are made…

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

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

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

  33. Text boxes • Most normal control! • Show test • data from for example databases • Lots of features…

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

  35. Text box methods • Interesting methoder: • Clear: remove content • Cut, Copy, Paste: interaction with clipboard • Undo: undo last change in textbox • Select, SelectAll: chose some of the content

  36. Text box events • Intereresting events: • Enter, Leave: appears when focus changes • KeyPress: appears when some ascii button is activated • KeyDown, KeyUp: appears with keyboard combinations • TextChanged: appears when text changes • Validating and Validated • Validating makes it possible to reject invalid input

  37. 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 } }

  38. 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?

  39. 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; } }

  40. 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: True if choosen, False if not • CheckedChanged appears when "Checked“ is changed

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

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

  43. Warnings • Don’t write code where the order of events matters… • The orders is never garantied • Every event is independent from others • Some kode trigger events behimd the code… • A natural sideeffect of event-drevet programmering this.textBox1.Text = "new value" // triggers TextChanged

  44. Only a small part of it all… • Menuer, dialoger, toolbars, etc. • Tousend of other controls • .NET and ActiveX • Rightclick onToolbox • "Customize Toolbox"

  45. 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!!!

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

More Related