chapter 4 windows forms gui/edp yingcai xiao. .net gui forms and controls

37
Chapter 4 Windows Forms GUI/EDP Yingcai Xiao

Post on 20-Dec-2015

229 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Chapter 4Windows Forms

GUI/EDP

Yingcai Xiao

Page 2: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

.NET GUIForms and Controls

Page 3: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Concepts: GUI Windows Forms—for writing GUI based applications

(Windows Applications).

GUI: Graphical User Interface, to make programs easy to use, WYSIWYG (What you see is what you get).

Designing GUI-based Applications: Look & FeelLook => Appearance (Layout Design)Feel => Response (Event Handling) User => Button Click => Event => Event Handler (a method).GUI-based application => Event-driven programming

• Two main tasks of GUI-based EDP:Design interface appearance (look)Implement even handlers (feel).

Page 4: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Concepts: GUI Design Principles

Users first: let users control the program not the other way around.

Elegant: simple but powerful. E.g.: iPot, iPhone, Google Intuitive: don’t need too much training to use it. Compare

operating interfaces of cars and airplanes. Clarity: use icons and keywords that are standardized or clearly

defined. (AWK?). Give users hints when they hesitating. Hierarchical: only put the most frequently used and most

important controls at the top level. Speedy: users do not have patience to wait for too long. Forgiving: allow users to make mistakes. Undo and redo. Alignment: use tables. Internationalization: use symbols. More: http://www.iie.org.mx/Monitor/v01n03/ar_ihc2.htm

http://www.asktog.com/basics/firstPrinciples.html

Page 5: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

.NET GUI Classes (Event Generators)

GUI Items are defined in System.Windows.Forms.System.Windows.Forms.Form class: all forms derive from it.

Properties (can be treated as “public” data members): ClientRectangle (drawing area not including the borders)

ClientSizeBorderStyleText (Title Bar)

Methods: OnPaint (event handler for the PAINT event)

Page 6: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

System.Windows.Forms Control Classes 

Controls (Windows GUI Items)

Class Descriptionss

Button Push buttons

CheckBox Check boxes

CheckedListBox List boxes whose items include check boxes

ComboBox Combo boxes

DataGrid Controls that display tabular data

DataGridTextBox Edit controls hosted by DataGrid controls

DateTimePicker Controls for selecting dates and times

Page 7: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Controls (Windows GUI Items) Cont.

System.Windows.Forms Control Classes 

GroupBox Group boxes

HScrollBar Horizontal scroll bars

Label Label controls that display static text

LinkLabel Label controls that display

hyperlinks

ListBox List boxes

ListView List views (display flat lists of items in a variety of

styles)

MonthCalendar Month-calendar controls

Page 8: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Controls (Windows GUI Items) Cont.

System.Windows.Forms Control Classes 

NumericUpDown Spinner buttons (up-down

controls)

PictureBox Controls that display

images PrintPreviewControl Controls that display print

previews

ProgressBar Progress bars

PropertyGrid Controls that list the properties of other objects

RadioButton Radio buttons

RichTextBox Rich-edit controls

Page 9: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Controls (Windows GUI Items) Cont.

System.Windows.Forms Control Classes 

StatusBar Status bars

TabControl Tab controls

TextBox Edit controls

ToolBar Toolbars

ToolTip Tooltips

TrackBar Track bars (slider controls)

TreeView Tree views (display hierarchical lists of items)

VScrollBar Vertical scroll bars

Page 10: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Programming a GUI APP using VS

1. Start Visual Studio2. New project3. Windows Forms Application4. Toolbox->Button: drag it to Form15. Double click on button1 in Form16. Add to button1_Click

this->button1->Text = "Hello!";

Build and run

Page 11: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Programming a GUI APP using Notepad

1. Use Notepad to write the program2. Create your form (GUI) by sub-classing System.Windows.Forms.Form.3. Add controls (GUI items) to the form. 4. Code your program logic.5. Compile the program using csc.

Example:T:\Xiao\Windows Programming\Examples\C4\DialogDemo\DialogDemo.cs

Page 12: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Programming a Control

1. Instantiate the corresponding control class.2. Initialize the control by setting its property values.3. Add the control to the form by calling

the “Add” method of the form’s Controls collection.4. Map event handlers to the events.5. Implement the event handlers.

Page 13: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Adding a Button to a Form

//Create and initialize the buttonButton MyButton = new Button ();MyButton.Location = new Point (16, 16);MyButton.Size = new Size (96, 24);MyButton.Text = "Click Me";

// add the button to the form’s Controls collection.Controls.Add (MyButton);

// Add event handlers to eventsMyButton.Click += new EventHandler (OnButtonClicked);

// Write the event handlers void OnButtonClicked (Object sender, EventArgs e){… }

T:\Xiao\Windows Programming\Examples\C4\DialogDemo\DialogDemo.cs

Page 14: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Common Dialog Classes Defined in System.Windows.Forms

Dialog Boxes

Class Dialog Type ColorDialog Color dialog boxes for choosing

colors FontDialog Font dialog boxes for choosing fonts OpenFileDialog Open File dialog boxes for choosing

files

PageSetupDialog Page Setup dialog boxes for entering page setup parameters

PrintDialog Print dialog boxes for entering print

parameters SaveFileDialog Save File dialog boxes for entering

file names

Page 15: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

class MyDialog : Form{ Label WidthLabel; TextBox WidthBox; Button OKButton;

public int UserWidth { get { return Convert.ToInt32 (WidthBox.Text); } set { WidthBox.Text = value.ToString (); } }

public MyDialog () { // Initialize the dialog's visual properties ClientSize = new Size (296, 196); StartPosition = FormStartPosition.CenterParent; FormBorderStyle = FormBorderStyle.FixedDialog; Text = "Edit Ellipse"; ShowInTaskbar = false;

DialogDemo.cs

Page 16: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

// Create the dialog's controls WidthLabel = new Label (); WidthLabel.Location = new Point (16, 16); WidthLabel.Size = new Size (48, 24); WidthLabel.Text = "Width";

WidthBox = new TextBox (); WidthBox.Location = new Point (64, 12); WidthBox.Size = new Size (96, 24); WidthBox.TabIndex = 1;

DialogDemo.cs

Page 17: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

OKButton = new Button (); OKButton.Location = new Point (184, 12); OKButton.Size = new Size (96, 24); OKButton.TabIndex = 3; OKButton.Text = "OK"; OKButton.DialogResult = DialogResult.OK;

AcceptButton = OKButton;

// Add the controls to the dialog Controls.Add (WidthLabel); Controls.Add (WidthBox); Controls.Add (OKButton);} }

DialogDemo.cs

Page 18: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

DialogDemo.cs

// In the parent form who starts the dialog:MyDialog dlg = new MyDialog ();if (dlg.ShowDialog (this) == DialogResult.OK) {

MyWidth = dlg.UserWidth; // get the input from the formInvalidate (); // update the display of the parent form

}

Page 19: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

EDP

Page 20: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Concepts: EDP

Event-Driven Programming (EDP): Application waits (idles)

after initialization until the user generates an event trough an input device (keyboard, mouse, …). The OS dispatches the event to the application who owns the active window. The corresponding event handler(s) of the application is invoked to process the event.

Page 21: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Events

A menu in C++:

char c;bool done = false;while(!done) {

cout << “Please make your selection, q to end:”cin >> c;switch(c) {case “+”:

add( );break;

case “-”:sub( ); break;

case “q”:done = true; break;

}}

Event Loop

Event Mapping&

Even Dispatching

Event

Event Handler

Page 22: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

(1) Event Generators: keyboard, GUI items (buttons, menus, …), NUI

devices. (2) Events / Messages:

MouseClick, KeyDown, …(3) Event Loop:

an infinite loop constantly waits for events. (4) Event Mapping / Event Registration:

inform event dispatcher which event an event hander is for.

(5) Event Dispatcher: dispatch events to the corresponding event handlers.

(6) Event Handlers:methods for processing events.OnMouseClick(), …

Key Components of EDP

Page 23: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

(1) Event Generators- commonly used GUI items are predefined. - used by programmers / GUI designers.

(2) Events / Messages - commonly used ones predefined.

(3) Event Loop: - taken care of by .NET. (4) Event Mapping / Registration:

- implemented by .NET. - to be used by the programmers

with appropriate matching: event – delegate – even handler

(5) Event Dispatching: - taken care of by .NET. (6) Event Handlers

- to be implemented by programmers.

Key Components of EDP in .NET

Page 24: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

(1) GUI Items (Event Generators)System.Windows.Forms.FormButton, Dialog, ….

(2) Events: predefined Windows Messages:e.g. WM_KEYDOWN

(3) Event Loop:Built in System.Windows.Forms.Application Class: static Run( ) method starts an application’s event loop.

.NET EDP Classes

Page 25: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

(4) Event Mapping / Registration:System defined ones have their names fixed: e.g. OnPaint().Other handlers need to be registered to the events with their corresponding delegates by the programmer.e.g. :

MyButton.Click += new EventHandler (OnButtonClicked); The Resource Editor will do this automatically

when the programmer double-clicks on a button. (5) Event Dispatching:

Built in: HW->OS->Active Application->Event Object->Delegate:Invoke->Handlers. .

.NET EDP Classes

Page 26: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

(6) Event Handlers:Programmers’ work.void HandlerName (Object sender, EventArgs e) //sender can be omitted. HandlerName = “On” “EventName”e.g. OnKeyDown(Object sender, EventArgs e);

.NET based GUI EDP:①Identify needed GUI items; code or visually design GUI.②Identify related event; register event handlers with the

events via their delegates.③Implement event handlers.

.NET EDP Classes

Page 27: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Mouse and Keyboard Events/Handlers

OnKeyDown A key is pressed KeyEventArgs

OnKeyPress A character is typed on the keyboard

KeyPressEventArgs

OnKeyUp A key is released KeyEventArgs

OnMouseDown A mouse button is pressed MouseEventArgs

OnMouseEnter The mouse cursor enters a form

EventArgs

OnMouseOver The mouse cursor pauses

over a form EventArgs

Page 28: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Mouse and Keyboard Events/Handlers

OnMouseLeave The mouse cursor leaves a form

EventArgs

OnMouseMove The mouse cursor moves over a form

MouseEventArgs

OnMouseUp A mouse button is

released MouseEventArgs

OnMouseWheel The mouse wheel is rolled

MouseEventArgs

Page 29: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

WM_KEYDOWN protected override void OnKeyDown (KeyEventArgs e) { // from the form     if (e.KeyCode == Keys.F1) // Function key F1 was pressed { … }}

WM_CHAR protected override void OnKeyPress (KeyPressEventArgs e){    

if (e.KeyChar == 'C') { … } // Do something

}

Mouse and Keyboard Events/Handlers

Page 30: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Other Form-Level Events

OnActivated A form is activated

OnClosed A form is closed

OnClosing A form is about to close

OnDeactivate A form is deactivated

OnGotFocus A form receives the input focus

OnLoad A form is created

OnLocationChanged A form is moved

OnLostFocus A form loses the input focus

OnPaintBackground A form’s background needs repainting

OnSizeChanged A form is resized

Page 31: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

// Create a MainMenu objectMainMenu menu = new MainMenu ();

// Add a File menu and populate it with itemsMenuItem item = menu.MenuItems.Add ("&File");item.MenuItems.Add ("&New", new EventHandler (OnFileNew));item.MenuItems.Add ("&Open...", new EventHandler (OnFileOpen));

// Add an Edit menu and populate it, tooitem = menu.MenuItems.Add ("&Edit");item.MenuItems.Add ("Cu&t", new EventHandler (OnEditCut));

Processing Menu Commandsvoid HandlerName (Object sender, EventArgs e)

Main Menus: top-level menu.

Page 32: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Context Menus: pop up context menus

ContextMenu menu = new ContextMenu ();menu.MenuItems.Add ("&Open", new EventHandler (OnOpen));menu.MenuItems.Add ("&Rename", new EventHandler (OnRename));menu.MenuItems.Add ("&Delete", new EventHandler (OnDelete));menu.Show (this, new Point (x, y));

Menu Item States: item.Checked = true;

Context Menus

Page 33: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Shortcut keys: key combinations to directly invoke a commande.g. Control O to open a fileitem.MenuItems.Add (new MenuItem ("&Open...",

new EventHandler (OnFileOpen), Shortcut.CtrlO)); http://www.computerhope.com/shortcut.htm

• Keyboard Accelerators: to help accessing a menu item without using the mouse. An accelerator key related to a menu item is preceded with an “&” and is displayed underlined.

e.g. Alt F to access the File menus, then O to open a fileitem.MenuItems.Add (new MenuItem ("&Open...",

new EventHandler (OnFileOpen), Shortcut.CtrlO)); Microsoft defines Keyboard Accelerators the same as Shortcuts.http://msdn.microsoft.com/en-us/library/ms645526(VS.85).aspx

Shortcuts and Accelerators

Page 34: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

.NET Drawing Classes: in System.Drawing.

Graphics Device Interface (GDI) software to interface with the graphics hardware.

GDI+ Graphics Primitives (System.Drawing.Drawing2D): Bitmap, Font, HatchBrush, LinearGradientBrush, Pen, SolidBrush, TextureBrush, DrawArc, DrawCurve, DrawEllipse, DrawIcon, DrawImage, DrawLine, DrawPie, DrawPolygon, DrawString, FillEllipse, FillPie, FillPolygon, FillRectangle.

Drawing in .NET

Page 35: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

GDI+ : stateless, a form passes parameters detailing output characteristics to every Graphics method it calls. For (stateless) Internet use.

Old Windows GDI: stateful, drawing parameters are stored as state variables in the GDI’s device context.

Example: DialogDemo.cs – OnPaint(PaintEventArgs e)

Dispose your GDI+ Objects to avoid running out of GDI+ resourses. e.g. brush.Dispose();

Drawing in .NET cont.

Page 36: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

DirectX: Direct3D, DirectMusic, DirectSound. Xbox (based on DirectX): Video GameXNA (Xbox New Architecture, XNA is Not an Acronym):

Video Game development and management

WPF: Windows Presentation Foundation Introduced in .NET 3.0 Based on DirectX, not GDI 2D and 3D

GDI and Beyond

Page 37: Chapter 4 Windows Forms GUI/EDP Yingcai Xiao. .NET GUI Forms and Controls

Summary

GUI-based windows application development:

GUI-based programming. forms and controls, look and feelEDPevents and handlersGDI