object oriented programming graphical user interfaces dr. mike spann [email protected]

46
Object Oriented Programming Graphical User Graphical User Interfaces Interfaces Dr. Mike Spann Dr. Mike Spann [email protected] [email protected]

Upload: bryce-garrison

Post on 29-Dec-2015

230 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Object Oriented Programming

Graphical User InterfacesGraphical User Interfaces

Dr. Mike SpannDr. Mike Spann

[email protected]@bham.ac.uk

Page 2: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Contents

IntroductionIntroduction Creating a simple GUICreating a simple GUI Visual programmingVisual programming Example – A simple image viewerExample – A simple image viewer Mouse event handlingMouse event handling Using HelpUsing Help SummarySummary

Page 3: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Introduction Most modern applications come with a sophisticated user Most modern applications come with a sophisticated user

interface comprisinginterface comprising Push buttonsPush buttons Selection boxesSelection boxes Dialog boxesDialog boxes Pull down menusPull down menus etcetc

This lecture focuses on the use of the classes found in the This lecture focuses on the use of the classes found in the System.Windows.FormsSystem.Windows.Forms namespace in the FCL to create these namespace in the FCL to create these user interfacesuser interfaces These are the classes that you will use if you are writing These are the classes that you will use if you are writing

client-side GUI applications with the .NET Frameworkclient-side GUI applications with the .NET Framework

Page 4: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Introduction

For even moderately sophisticated GUI’s, it is advisable to For even moderately sophisticated GUI’s, it is advisable to use visual programming techniques under Visual Studiouse visual programming techniques under Visual Studio A lot of code is automatically generatedA lot of code is automatically generated Easy placement of GUI componentsEasy placement of GUI components Extensive use of properties to customize our GUI Extensive use of properties to customize our GUI

componentscomponents Essentially all we need to do is write the event handlersEssentially all we need to do is write the event handlers

However, it is important to understand how it all works and However, it is important to understand how it all works and how we could write GUI’s ourselves from scratchhow we could write GUI’s ourselves from scratch

Page 5: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Introduction The The FormForm class is a basic outer container which class is a basic outer container which

then holds GUI components such as menus, then holds GUI components such as menus, buttons and checkboxesbuttons and checkboxes

Usually GUI’s comprise a class derived from Usually GUI’s comprise a class derived from FormForm to create a specialization that fits the need of to create a specialization that fits the need of the applicationthe application

using System.Windows.Forms;

class App{ public static void Main() { Application.Run(new Form()); }}

Page 6: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Introduction

This programs produces a simple outer container with basic windows This programs produces a simple outer container with basic windows functionality that we are familiar withfunctionality that we are familiar with Maximize buttonMaximize button Minimize buttonMinimize button etcetc

We can easily add components to this to specialize its behaviourWe can easily add components to this to specialize its behaviour

Page 7: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Creating a simple GUI

We can create a GUI containing a button and add We can create a GUI containing a button and add an event handler to provide some functionalityan event handler to provide some functionality

Normally much of this code would be generated Normally much of this code would be generated automatically using visual programming automatically using visual programming techniquestechniques We would just have to add the event handling We would just have to add the event handling

code to specify the behaviour we requirecode to specify the behaviour we require In this case a simple pop up message box is In this case a simple pop up message box is

displayeddisplayed

Page 8: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Creating a simple GUIusing System;using System.Windows.Forms;

class App{ public static void Main() { Application.Run(new MySimpleForm()); }}

class MySimpleForm : Form{ public MySimpleForm() { Button button = new Button(); button.Text = "My Button"; button.Click += new EventHandler(OnClick);

this.Controls.Add(button); }

void OnClick(Object sender, EventArgs args) { MessageBox.Show("The Button Was Clicked!"); }}

Page 9: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Creating a simple GUI

Demos\Simple Form\MySimpleForm.exe

Page 10: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Visual programming Visual programming allows us to create GUI’s in Visual programming allows us to create GUI’s in designer view designer view

using Visual Studiousing Visual Studio It involves dragging and dropping GUI components from a It involves dragging and dropping GUI components from a

toolbox onto an outer toolbox onto an outer FormForm container container If we select the If we select the Windows ApplicationWindows Application project template, we project template, we

automatically get the project up in designer view with a small automatically get the project up in designer view with a small amount of pre-generated codeamount of pre-generated code

We can drag GUI components from the toolbox onto our form and We can drag GUI components from the toolbox onto our form and position them as we wishposition them as we wish

Clicking on a component (eg a button), adds an event handler for Clicking on a component (eg a button), adds an event handler for that component and the view changes from designer view to code that component and the view changes from designer view to code view allowing us to add code for the event handlerview allowing us to add code for the event handler

Page 11: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk
Page 12: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Visual programming

For example we can re-create our simple GUI For example we can re-create our simple GUI and only have to write 1 line of code!!and only have to write 1 line of code!!

Also we can easily customize the look of the Also we can easily customize the look of the GUI by updating the propertiesGUI by updating the properties Button textButton text Background colourBackground colour Button placementButton placement etcetc

Page 13: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk
Page 14: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Visual programmingusing System;using System.Windows.Forms;

namespace MySimpleForm_VP{ public partial class Form1 : Form { public Form1() { InitializeComponent(); }

private void button1_Click(object sender, EventArgs e) {

// User code here!! MessageBox.Show("The Button Was Clicked!"); } }}

Page 15: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Visual programming

Automatically generated code is put in the Automatically generated code is put in the xxxx.Designer.csxxxx.Designer.cs file file The The InitializeComponentInitializeComponent method method

involves creating the GUI components involves creating the GUI components and their properties and registering event and their properties and registering event handlershandlers

Also a main method is automatically Also a main method is automatically generated which calls generated which calls Application.Run(...)Application.Run(...)

Page 16: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

namespace MySimpleForm_VP{ partial class Form1 { .

.

. #region Windows Form Designer generated code

private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(-1, 0); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "My button"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 266); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false);

}

#endregion

private System.Windows.Forms.Button button1; }}

Page 17: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

using System;using System.Windows.Forms;

namespace MySimpleForm_VP{ static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } }}

Page 18: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Visual programming

The code is automatically updated when we The code is automatically updated when we customize our GUI appearance using the customize our GUI appearance using the VS properties windowVS properties window

Page 19: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk
Page 20: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Visual Designer demo

Page 21: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Example – A simple image viewer We can create a simple image viewer for We can create a simple image viewer for

loading and displaying images loading and displaying images We will use visual programming and write a We will use visual programming and write a

small amount of codesmall amount of code This example will introduce the following This example will introduce the following

GUI componentsGUI components MenusMenus File dialogue boxesFile dialogue boxes

Page 22: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Example – A simple image viewer Menus can be easily added to a Menus can be easily added to a FormForm in design in design

viewview A A MenuStripMenuStrip is dragged across from the toolbox to is dragged across from the toolbox to

create the menu barcreate the menu bar Textboxes are then available to type in the names Textboxes are then available to type in the names

of the menu’s and menu itemsof the menu’s and menu items This can be repeated for sub menu’s This can be repeated for sub menu’s Shortcuts can be added by entering an & before Shortcuts can be added by entering an & before

the namethe name

Page 23: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

menustrip icon

menu

menu items

Page 24: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Example – A simple image viewer

We can add an We can add an OpenFileDialogOpenFileDialog box by box by dragging it from the toolboxdragging it from the toolbox

We also automatically add function headers We also automatically add function headers for each event handler by clicking on the for each event handler by clicking on the menu items and the menu items and the OpenFileDialogOpenFileDialog icon icon The only code we need are the function The only code we need are the function

bodies of the event handlersbodies of the event handlers

Page 25: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk
Page 26: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

public partial class Form1 : Form{ private readonly string initialImageDirectory=

"C:\\Documents and Settings\\spannm\\Desktop\\Personal Stuff\\Images";

private Image loadedImage = null;

public Form1() { InitializeComponent(); openFileDialog1.InitialDirectory=initialImageDirectory; }

private void openToolStripMenuItem_Click(object sender, EventArgs e) { // Open image file dialog box and load an image openFileDialog1.ShowDialog(); }

private void exitToolStripMenuItem_Click(object sender, EventArgs e) {

// Exit application Application.Exit(); }

private void closeToolStripMenuItem_Click(object sender, EventArgs e) { // Close the image }

private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { string fileName = openFileDialog1.FileName; if (fileName.Length != 0) { // Load the image } }}

Page 27: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Example – A simple image viewer

We need to decide how we wish to display the imageWe need to decide how we wish to display the image We could drag a We could drag a PictureBoxPictureBox component inside the component inside the

formformThis then displays the image inside the This then displays the image inside the Form Form

containercontainer It’s much more realistic to have the image in a It’s much more realistic to have the image in a

completely independent windowcompletely independent window This requires us to build a separate This requires us to build a separate ImageFormImageForm

classclass

Page 28: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Example – A simple image viewer

We can create a separate windows application We can create a separate windows application comprising a comprising a FormForm containing a containing a PictureBoxPictureBox The The PictureBoxPictureBox class has an class has an ImageImage property property

which is the image it is displayingwhich is the image it is displaying The The Load()Load() event handler displays the image event handler displays the image

when the form is createdwhen the form is created All very easy to do in design view of VSAll very easy to do in design view of VS

Page 29: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk
Page 30: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Example – A simple image viewer

public partial class ImageForm : Form{ private Image image;

public ImageForm(Image im) { image = im; InitializeComponent(); }

private void ImageForm_Load(object sender, EventArgs e) { pictureBox1.Image = image; }}

Page 31: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Example – A simple image viewer The only real code we have to write is the event The only real code we have to write is the event

handler for loading and displaying an image from filehandler for loading and displaying an image from file This appears in the This appears in the openFileDialog1_FileOk() openFileDialog1_FileOk()

event handler which is called when the open file event handler which is called when the open file dialog box ‘OK’ button is presseddialog box ‘OK’ button is pressed

An An ImageFormImageForm object is created and the loaded object is created and the loaded image passed to its constructorimage passed to its constructor

Minimal code for a fairly sophisticated applicationMinimal code for a fairly sophisticated application

Page 32: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Example – A simple image viewer

public partial class Form1 : Form{ private Image loadedImage = null; private ImageForm imageForm = null;

.

. private void closeToolStripMenuItem_Click(object sender, EventArgs e) { // Close the image

if (imageForm != null) imageForm.Close(); }

private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { string fileName = openFileDialog1.FileName;

if (fileName.Length != 0) { // Display the loaded image loadedImage = Image.FromFile(fileName); imageForm = new ImageForm(loadedImage); imageForm.Show(); } }}

Page 33: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Example – A simple image viewer Demos\Basic Image Viewer\Image Viewer

Basic.exe

Page 34: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Example – A simple image viewer

It’s easy to change both the look and the behaviour of the It’s easy to change both the look and the behaviour of the tool without additional codetool without additional code We simply change propertiesWe simply change properties For example, we can change how the image is displayed For example, we can change how the image is displayed

by altering the by altering the SizeModeSizeMode property of the property of the PictureBoxPictureBox SizeMode=Normal SizeMode=Normal - displays image without scaling - displays image without scaling

in the top left hand corner of the in the top left hand corner of the PictureBoxPictureBox SizeMode=AutoSize – SizeMode=AutoSize – resizes the resizes the PictureBox PictureBox to hold to hold

the imagethe image etcetc

Page 35: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Example – A simple image viewer

SizeMode=AutoSize SizeMode=Normal

Page 36: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Mouse event handling Mouse events occur when the user clicks, presses and moves Mouse events occur when the user clicks, presses and moves

the mousethe mouse Being able to handle mouse events can lead to highly Being able to handle mouse events can lead to highly

interactive applicationsinteractive applications Information about the mouse event is passed to an event Information about the mouse event is passed to an event

handling method through an object of class handling method through an object of class MouseEventArgs MouseEventArgs or or EventArgsEventArgs Typically this might be the x and y coordinates of the Typically this might be the x and y coordinates of the

position of the mouse cursorposition of the mouse cursor The delegate used to create the event handlers is The delegate used to create the event handlers is

MouseEventHandlerMouseEventHandler

Page 37: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Mouse event handling

Mouse events and event arguments

Mouse Events with Event Argument of Type EventArgs

MouseEnter Occurs when the mouse cursor enters the control’s boundaries.

MouseLeave Occurs when the mouse cursor leaves the control’s boundaries.

Mouse Events with Event Argument of Type MouseEventArgs

MouseDown Occurs when a mouse button is pressed while the mouse cursor is within a control’s boundaries.

MouseHover Occurs when the mouse cursor hovers within the control’s boundaries.

MouseMove Occurs when the mouse cursor is moved while in the control’s boundaries.

MouseUp Occurs when a mouse button is released when the cursor is within the control’s boundaries.

Class MouseEventArgs Properties

Button Specifies which mouse button was pressed (Left, Right, Middle or none).

Clicks The number of times the mouse button was clicked.

X The x-coordinate within the control where the event occurred.

Y The y-coordinate within the control where the event occurred.

We can summarise mouse events and event We can summarise mouse events and event properties as follows:properties as follows:

Page 38: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Mouse event handling

For example, we can paint graphics on the image as For example, we can paint graphics on the image as displayed in our image viewerdisplayed in our image viewer

We make use of the We make use of the MouseDown, MouseUp MouseDown, MouseUp and and MouseMoveMouseMove events events

With the With the ImageForm ImageForm in design view, we click on the in design view, we click on the mouse events for which we wish to add event handlersmouse events for which we wish to add event handlers Automatic code is generated for the empty Automatic code is generated for the empty

functionsfunctions We need to fill in the function bodiesWe need to fill in the function bodies

Page 39: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk
Page 40: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

For example, we can combine the For example, we can combine the MouseDownMouseDown and and MouseMove MouseMove event handler to draw event handler to draw freehand graphics as we move the mouse freehand graphics as we move the mouse

Or we can just select coordinates on the image Or we can just select coordinates on the image using using MouseDownMouseDown and draw the rectangle and draw the rectangle through opposing verticesthrough opposing vertices Useful in selecting a region of interest in an Useful in selecting a region of interest in an

image processing applicationimage processing application

Mouse event handling

Page 41: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Mouse event handlingpublic partial class ImageForm : Form{ private Image image;

private bool shouldPaint = false;

public ImageForm(Image im) { image = im; InitializeComponent(); }

private void ImageForm_MouseMove(object sender, MouseEventArgs e) { if (shouldPaint) { Graphics graphics = CreateGraphics();

graphics.FillEllipse(new SolidBrush(Color.Blue), e.X, e.Y, 4, 4); graphics.Dispose(); } }

private void ImageForm_MouseDown(object sender, MouseEventArgs e){shouldPaint = true;}

private void ImageForm_MouseUp(object sender, MouseEventArgs e) {shouldPaint = false;}

private void ImageForm_Paint(object sender, PaintEventArgs e) { Graphics graphics = e.Graphics; graphics.DrawImage(image, new Point(20,20)); }}

Page 42: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Mouse event handling

Demos\Image Viewer Free Draw\Image Viewer.exe

Page 43: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Mouse event handlingpublic partial class ImageForm : Form{ private Image image;

private int startX=-1; private int startY, endX, endY;

public ImageForm(Image im) { image = im; InitializeComponent(); }

private void ImageForm_MouseDown(object sender, MouseEventArgs e) { if (startX < 0) { startX = e.X; startY = e.Y; } else { endX = e.X; endY = e.Y; Graphics graphics = CreateGraphics(); Pen whitePen = new Pen(Color.White, 2); graphics.DrawRectangle(whitePen,

new Rectangle(startX,startY,endX-startX,endY-startY)); } } private void ImageForm_Paint(object sender, PaintEventArgs e) { Graphics graphics = e.Graphics;

graphics.DrawImage(image, new Point(20,20)); }}

Page 44: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Mouse event handling

Demos\Image Viewer ROI\Image Viewer.exe

Page 45: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Mouse event handling

Both these examples use the Both these examples use the Graphics Graphics object and other object and other objects in the objects in the System.Drawing System.Drawing namespace such as namespace such as PenPen and and SoilidBrushSoilidBrush More about these concepts in the lecture on graphics More about these concepts in the lecture on graphics

and multimediaand multimedia We use the We use the Graphics.DrawImage()Graphics.DrawImage() method to draw the method to draw the

image in the image in the Paint()Paint() event handler event handler Paint()Paint() is called automatically whenever the form is called automatically whenever the form

needs repaintingneeds repaintingFor example when the form is moved or resizedFor example when the form is moved or resized

Page 46: Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk

Summary

We have seen how we can create a simple GUI and We have seen how we can create a simple GUI and add an event handler to determine the behaviour of the add an event handler to determine the behaviour of the GUIGUI

We have also seen how we can do the same thing We have also seen how we can do the same thing much simpler using visual programming techniquesmuch simpler using visual programming techniques

We have looked at a simple image viewer application We have looked at a simple image viewer application which uses a menu and a file input dialog boxwhich uses a menu and a file input dialog box

We have looked at how we can handle mouse eventsWe have looked at how we can handle mouse events