470 likes | 663 Views
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…”
E N D
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
Part 1 • Event-drevet, code-behind programing…
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
Eksamples on GUI-baserede events • Mouse move • Mouse click • Mouse double-click • Key press • Button click • Menu selection • Change in focus • Window activation • etc.
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…
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.
Part 2 • Visual Studio .NET…
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.
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…
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…
Step 1 • Make a new project of type “Windows Application” • VS. will automatically make a form…
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
GUI design … • A simple calculator: • Place and configure controls • Click to chose • set properties viathe Properties-window
Step 3 — codedesign • Implement the forms “Code behind”… • Dobbelt-clik on the control you want to implement – the eventhandler is generated
Step 4 — run mode • Run!
Break mode? • Is started in this appI for example by typing something wrong…
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
Part 3 • WinForms…
WinForms • Another name for traditional, Windowslike GUI-applications • Unlike WebForms, which is web-based • Is implementer via FCL • Portable to any .NET platform
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
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();
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
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
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; }
Part 4 • Controls…
Controls • Userinterfaceobjecter på formen: • labels • buttons • text boxes • menus • list & combo boxes • option buttons • check boxes • etc.
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
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…
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
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
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
Text boxes • Most normal control! • Show test • data from for example databases • Lots of features…
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
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
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
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 } }
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?
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; } }
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
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);
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);
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
Only a small part of it all… • Menuer, dialoger, toolbars, etc. • Tousend of other controls • .NET and ActiveX • Rightclick onToolbox • "Customize Toolbox"
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!!!
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)