Object Oriented Programming Graphical User Interfaces Dr. Mike Spann m.spann@bham.ac.uk Contents Introduction Creating a simple GUI Visual programming Example – A simple image viewer Mouse event handling Using Help Summary Introduction Most modern applications come with a sophisticated user interface comprising Push buttons Selection boxes Dialog boxes Pull down menus etc This lecture focuses on the use of the classes found in the System.Windows.Forms namespace in the FCL to create these user interfaces These are the classes that you will use if you are writing client-side GUI applications with the .NET Framework Introduction For even moderately sophisticated GUI’s, it is advisable to use visual programming techniques under Visual Studio A lot of code is automatically generated Easy placement of GUI components Extensive use of properties to customize our GUI components Essentially all we need to do is write the event handlers However, it is important to understand how it all works and how we could write GUI’s ourselves from scratch Introduction The Form class is a basic outer container which then holds GUI components such as menus, buttons and checkboxes Usually GUI’s comprise a class derived from Form to create a specialization that fits the need of the application using System.Windows.Forms; class App { public static void Main() { Application.Run(new Form()); } } Introduction This programs produces a simple outer container with basic windows functionality that we are familiar with Maximize button Minimize button etc We can easily add components to this to specialize its behaviour Creating a simple GUI We can create a GUI containing a button and add an event handler to provide some functionality Normally much of this code would be generated automatically using visual programming techniques We would just have to add the event handling code to specify the behaviour we require In this case a simple pop up message box is displayed Creating a simple GUI using 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!"); } } Creating a simple GUI Demos\Simple Form\MySimpleForm.exe Visual programming Visual programming allows us to create GUI’s in designer view using Visual Studio It involves dragging and dropping GUI components from a toolbox onto an outer Form container If we select the Windows Application project template, we automatically get the project up in designer view with a small amount of pre-generated code We can drag GUI components from the toolbox onto our form and position them as we wish Clicking on a component (eg a button), adds an event handler for that component and the view changes from designer view to code view allowing us to add code for the event handler Visual programming For example we can re-create our simple GUI and only have to write 1 line of code!! Also we can easily customize the look of the GUI by updating the properties Button text Background colour Button placement etc Visual programming using 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!"); } } } Visual programming Automatically generated code is put in the xxxx.Designer.cs file The InitializeComponent method involves creating the GUI components and their properties and registering event handlers Also a main method is automatically generated which calls Application.Run(...) 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; } } 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()); } } } Visual programming The code is automatically updated when we customize our GUI appearance using the VS properties window Visual Designer demo Example – A simple image viewer We can create a simple image viewer for loading and displaying images We will use visual programming and write a small amount of code This example will introduce the following GUI components Menus File dialogue boxes Example – A simple image viewer Menus can be easily added to a Form in design view A MenuStrip is dragged across from the toolbox to create the menu bar Textboxes are then available to type in the names of the menu’s and menu items This can be repeated for sub menu’s Shortcuts can be added by entering an & before the name menu menu items menustrip icon Example – A simple image viewer We can add an OpenFileDialog box by dragging it from the toolbox We also automatically add function headers for each event handler by clicking on the menu items and the OpenFileDialog icon The only code we need are the function bodies of the event handlers 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 } } } Example – A simple image viewer We need to decide how we wish to display the image We could drag a PictureBox component inside the form This then displays the image inside the Form container It’s much more realistic to have the image in a completely independent window This requires us to build a separate ImageForm class Example – A simple image viewer We can create a separate windows application comprising a Form containing a PictureBox The PictureBox class has an Image property which is the image it is displaying The Load() event handler displays the image when the form is created All very easy to do in design view of VS 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; } } Example – A simple image viewer The only real code we have to write is the event handler for loading and displaying an image from file This appears in the openFileDialog1_FileOk() event handler which is called when the open file dialog box ‘OK’ button is pressed An ImageForm object is created and the loaded image passed to its constructor Minimal code for a fairly sophisticated application 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(); } } } Example – A simple image viewer Demos\Basic Image Viewer\Image Viewer Basic.exe Example – A simple image viewer It’s easy to change both the look and the behaviour of the tool without additional code We simply change properties For example, we can change how the image is displayed by altering the SizeMode property of the PictureBox SizeMode=Normal - displays image without scaling in the top left hand corner of the PictureBox SizeMode=AutoSize – resizes the PictureBox to hold the image etc Example – A simple image viewer SizeMode=AutoSize SizeMode=Normal Mouse event handling Mouse events occur when the user clicks, presses and moves the mouse Being able to handle mouse events can lead to highly interactive applications Information about the mouse event is passed to an event handling method through an object of class MouseEventArgs or EventArgs Typically this might be the x and y coordinates of the position of the mouse cursor The delegate used to create the event handlers is MouseEventHandler Mouse event handling We can summarise mouse events and event properties as follows: 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. Mouse event handling For example, we can paint graphics on the image as displayed in our image viewer We make use of the MouseDown, MouseUp and MouseMove events With the ImageForm in design view, we click on the mouse events for which we wish to add event handlers Automatic code is generated for the empty functions We need to fill in the function bodies Mouse event handling For example, we can combine the MouseDown and MouseMove event handler to draw freehand graphics as we move the mouse Or we can just select coordinates on the image using MouseDown and draw the rectangle through opposing vertices Useful in selecting a region of interest in an image processing application Mouse event handling public 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)); } } Mouse event handling Demos\Image Viewer Free Draw\Image Viewer.exe Mouse event handling public partial { private private private class ImageForm : Form Image image; int startX=-1; 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)); } } Mouse event handling Demos\Image Viewer ROI\Image Viewer.exe Mouse event handling Both these examples use the Graphics object and other objects in the System.Drawing namespace such as Pen and SoilidBrush More about these concepts in the lecture on graphics and multimedia We use the Graphics.DrawImage() method to draw the image in the Paint() event handler Paint() is called automatically whenever the form needs repainting For example when the form is moved or resized Summary We have seen how we can create a simple GUI and add an event handler to determine the behaviour of the GUI We have also seen how we can do the same thing much simpler using visual programming techniques We have looked at a simple image viewer application which uses a menu and a file input dialog box We have looked at how we can handle mouse events