46
WinForms: GUI Programming in .NET

WinForms: GUI Programming in .NET

  • Upload
    sauda

  • View
    124

  • Download
    11

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

Page 1: WinForms:   GUI Programming in .NET

WinForms: GUI Programming in .NET

Page 2: 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

Page 3: WinForms:   GUI Programming in .NET

3UCN 2012

Part 1

• Event-drevet, code-behind programing…

Page 4: WinForms:   GUI Programming in .NET

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

Page 5: WinForms:   GUI Programming in .NET

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.

Page 6: WinForms:   GUI Programming in .NET

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…

Page 7: WinForms:   GUI Programming in .NET

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.

Page 8: WinForms:   GUI Programming in .NET

8UCN 2012

Part 2

• Visual Studio .NET…

Page 9: WinForms:   GUI Programming in .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.

Page 10: WinForms:   GUI Programming in .NET

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

Page 11: WinForms:   GUI Programming in .NET

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…

Page 12: WinForms:   GUI Programming in .NET

12UCN 2012

Step 1

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

Page 13: WinForms:   GUI Programming in .NET

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

Page 14: WinForms:   GUI Programming in .NET

14UCN 2012

GUI design …

• A simple calculator:

• Place and configure controls– Click to chose– set properties viathe Properties-window

Page 15: WinForms:   GUI Programming in .NET

15UCN 2012

Step 3 — codedesign

• Implement the forms “Code behind”…• Dobbelt-clik on the control you want to

implement – the eventhandler is generated

Page 16: WinForms:   GUI Programming in .NET

16UCN 2012

Step 4 — run mode

• Run!

Page 17: WinForms:   GUI Programming in .NET

17UCN 2012

Break mode?

• Is started in this appI for example by typing something wrong…

Page 18: WinForms:   GUI Programming in .NET

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

Page 19: WinForms:   GUI Programming in .NET

19UCN 2012

Part 3

• WinForms…

Page 20: WinForms:   GUI Programming in .NET

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

Page 21: WinForms:   GUI Programming in .NET

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

Page 22: WinForms:   GUI Programming in .NET

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();

Page 23: WinForms:   GUI Programming in .NET

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();

Page 24: WinForms:   GUI Programming in .NET

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

Page 25: WinForms:   GUI Programming in .NET

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

Page 26: WinForms:   GUI Programming in .NET

26UCN 2012

Part 4

• Controls…

Page 27: WinForms:   GUI Programming in .NET

27UCN 2012

Controls

• Userinterfaceobjecter på formen:

– labels– buttons– text boxes– menus– list & combo boxes– option buttons– check boxes– etc.

Page 28: WinForms:   GUI Programming in .NET

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

Page 29: WinForms:   GUI Programming in .NET

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…

Page 30: WinForms:   GUI Programming in .NET

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

Page 31: WinForms:   GUI Programming in .NET

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

Page 32: WinForms:   GUI Programming in .NET

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

Page 33: WinForms:   GUI Programming in .NET

33UCN 2012

Text boxes

• Most normal control!– Show test– data from for example databases

• Lots of features…

Page 34: WinForms:   GUI Programming in .NET

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

Page 35: WinForms:   GUI Programming in .NET

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

Page 36: WinForms:   GUI Programming in .NET

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

Page 37: WinForms:   GUI Programming in .NET

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

Page 38: WinForms:   GUI Programming in .NET

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?

Page 39: WinForms:   GUI Programming in .NET

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

Page 40: WinForms:   GUI Programming in .NET

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

Page 41: WinForms:   GUI Programming in .NET

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

Page 42: WinForms:   GUI Programming in .NET

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

Page 43: WinForms:   GUI Programming in .NET

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

Page 44: WinForms:   GUI Programming in .NET

44UCN 2012

Only a small part of it all…

• Menuer, dialoger, toolbars, etc.

• Tousend of other controls– .NET and ActiveX– Rightclick onToolbox– "Customize Toolbox"

Page 45: WinForms:   GUI Programming in .NET

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

Page 46: WinForms:   GUI Programming in .NET

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)