Upload
sauda
View
124
Download
11
Tags:
Embed Size (px)
DESCRIPTION
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…” - PowerPoint PPT Presentation
Citation preview
WinForms: GUI Programming in .NET
2UCN 2012
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
3UCN 2012
Part 1
• Event-drevet, code-behind programing…
4UCN 2012
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
5UCN 2012
Eksamples on GUI-baserede events
• Mouse move• Mouse click• Mouse double-click• Key press• Button click• Menu selection• Change in focus• Window activation• etc.
6UCN 2012
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…
7UCN 2012
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.
8UCN 2012
Part 2
• Visual Studio .NET…
9UCN 2012
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.
10UCN 2012
Basis operation
• Visual Studio operates in 1 of 3 ways:
1) design
2) run
3) break
• See VS title bar if you are in doubt…
design run
break
11UCN 2012
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…
12UCN 2012
Step 1
• Make a new project of type “Windows Application”– VS. will automatically make a form…
13UCN 2012
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
14UCN 2012
GUI design …
• A simple calculator:
• Place and configure controls– Click to chose– set properties viathe Properties-window
15UCN 2012
Step 3 — codedesign
• Implement the forms “Code behind”…• Dobbelt-clik on the control you want to
implement – the eventhandler is generated
16UCN 2012
Step 4 — run mode
• Run!
17UCN 2012
Break mode?
• Is started in this appI for example by typing something wrong…
18UCN 2012
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
19UCN 2012
Part 3
• WinForms…
20UCN 2012
WinForms
• Another name for traditional, Windowslike GUI-applications– Unlike WebForms,
which is web-based
• Is implementer via FCL– Portable to any .NET platform
21UCN 2012
Abstraction
• FCL works as an abstraction– parts WinForm app from the underlaying platform
System.Windows.Forms.Form
CLR
Windows OS
instance of
FCL classobject
22UCN 2012
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();
23UCN 2012
Form methods
• 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.Hide(); . . .
form.Show();
24UCN 2012
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
25UCN 2012
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;}
26UCN 2012
Part 4
• Controls…
27UCN 2012
Controls
• Userinterfaceobjecter på formen:
– labels– buttons– text boxes– menus– list & combo boxes– option buttons– check boxes– etc.
28UCN 2012
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
object
object
object
object
object
object
29UCN 2012
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…
30UCN 2012
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
31UCN 2012
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
32UCN 2012
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
33UCN 2012
Text boxes
• Most normal control!– Show test– data from for example databases
• Lots of features…
34UCN 2012
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
35UCN 2012
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
36UCN 2012
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
37UCN 2012
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 }}
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
38UCN 2012
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?
39UCN 2012
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; }}
40UCN 2012
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
41UCN 2012
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);
42UCN 2012
Customer[] customers; . . // create & fill array with objects... .
// display customers in list box foreach (Customer c in customers) this.listBox1.Items.Add(c);
List Boxes
• Good for visualising lists of data– Lists of strings– Lists of object (list box will call ToString())
// display name of selected customer (if any)Customer c;c = (Customer) this.listBox1.SelectedItem;if (c == null) return;else MessageBox.Show(c.Name);
43UCN 2012
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" // triggers TextChanged
44UCN 2012
Only a small part of it all…
• Menuer, dialoger, toolbars, etc.
• Tousend of other controls– .NET and ActiveX– Rightclick onToolbox– "Customize Toolbox"
45UCN 2012
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!!!
46UCN 2012
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)