1
C# cont’d(C-sharp)
(many of these slides are extracted and adapted from Deitel’s book and slides, “How to Program in C#”. They are provided for CSE3403 students only. Not to be
published or publicly distributed without permission by the publisher).
2
The code • using System;• using System.Drawing;• using System.Collections;• using System.ComponentModel;• using System.Windows.Forms;• using System.Data;• using System.IO;• namespace WindowsApplication3_6• {• /// <summary>• /// Summary description for Form1.• /// </summary>• public class Form1 : System.Windows.Forms.Form• {
• private System.Windows.Forms.PictureBox pictureBox1;• /// <summary>• /// Required designer variable.• /// </summary>• private System.ComponentModel.Container components = null;
• private int imageNum = -1;
• public Form1()• {• //• // Required for Windows Form Designer support• //• InitializeComponent();
• //• // TODO: Add any constructor code after InitializeComponent call• //• }
• /// <summary>• /// Clean up any resources being used.• /// </summary>• protected override void Dispose( bool disposing )• {• if( disposing )• {• if (components != null) • {• components.Dispose();• }• }• base.Dispose( disposing );• }
3
…• #region Windows Form Designer generated code• /// <summary>• /// Required method for Designer support - do not modify• /// the contents of this method with the code editor.• /// </summary>• private void InitializeComponent()• {
• System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
• this.pictureBox1 = new System.Windows.Forms.PictureBox();• this.SuspendLayout();• // • // pictureBox1• // • this.pictureBox1.BackColor = System.Drawing.SystemColors.ControlLightLight;• this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;• this.pictureBox1.Image = ((System.Drawing.Bitmap)(resources.GetObject("pictureBox1.Image")));• this.pictureBox1.Location = new System.Drawing.Point(16, 24);• this.pictureBox1.Name = "pictureBox1";• this.pictureBox1.Size = new System.Drawing.Size(384, 368);• this.pictureBox1.TabIndex = 0;• this.pictureBox1.TabStop = false;
• this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);• // • // Form1• // • this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);• this.BackColor = System.Drawing.SystemColors.Highlight;• this.ClientSize = new System.Drawing.Size(440, 429);• this.Controls.AddRange(new System.Windows.Forms.Control[] {•
this.pictureBox1});• this.Name = "Form1";• this.Text = "Form1";• this.ResumeLayout(false);
• }• #endregion
• /// <summary>• /// The main entry point for the application.• /// </summary>• [STAThread]• static void Main() • {• Application.Run(new Form1());• }
4
…• private void pictureBox1_Click(object sender, System.EventArgs e)• {• imageNum = ( imageNum + 1 ) % 3; // imageNum from 0 to 2• pictureBox1.Image = Image.FromFile(
Directory.GetCurrentDirectory() + "\\..\\..\\images\\image" + imageNum + ".bmp" );• }• }• }
5
Mouse Event Handling• Class MouseEventArgs
– Contain coordinates of the mouse pointer
– The mouse pressed– Number of clicks– Number of notches the wheel
turned– Passing mouse event– Mouse event-handling
methods take an object and MouseEventArgs object as argument
– The Click event uses delegate EventHandler and event arguments EventArgs
– (mouseHover :: idle the mouse once you enter) Available Mouse
events
6
Mouse Event HandlingMouse Events, Delegates and Event Arguments
Mouse Events (Delegate EventHandler, event arguments EventArgs)
MouseEnter Raised if the mouse cursor enters the area of the control. MouseLeave Raised if the mouse cursor leaves the area of the control. Mouse Events (Delegate MouseEventHandler, event arguments MouseEventArgs)
MouseDown Raised if the mouse button is pressed while its cursor is over the area of the control.
MouseHover Raised if the mouse cursor hovers over the area of the control. MouseMove Raised if the mouse cursor is moved while in the area of the control. MouseUp Raised if the mouse button is released when the cursor is over the area of the
control.
Class MouseEventArgs Properties
Button Mouse button that was pressed (left, right, middle or none). Clicks The number of times the mouse button was clicked. X The x-coordinate of the event, relative to the component. Y The y-coordinate of the event, relative to the component.
Mouse events, delegates and event arguments.
8
The code • using System;• using System.Drawing;• using System.Collections;• using System.ComponentModel;• using System.Windows.Forms;• using System.Data;
• namespace WindowsApplication4_1Mouse• {• /// <summary>• /// Summary description for Form1.• /// </summary>• public class Form1 : System.Windows.Forms.Form• {• private System.Windows.Forms.Label label1;• private System.Windows.Forms.Label label2;• private System.Windows.Forms.Label label3;• private System.Windows.Forms.Label label4;• private System.Windows.Forms.Label label5;• private System.Windows.Forms.TextBox textBox1;• private System.Windows.Forms.TextBox textBox2;• private System.Windows.Forms.TextBox textBox3;• private System.Windows.Forms.TextBox textBox4;• private System.Windows.Forms.TextBox textBox5;• private System.Windows.Forms.Panel panel1;• private System.Windows.Forms.Label label6;• private System.Windows.Forms.Label label7;• private System.Windows.Forms.TextBox textBox6;• /// <summary>• /// Required designer variable.• /// </summary>• private System.ComponentModel.Container components = null;
• public Form1()• {• //• // Required for Windows Form Designer support• //• InitializeComponent();
• //• // TODO: Add any constructor code after InitializeComponent call• //• }
9
...• /// <summary>• /// Clean up any resources being used.• /// </summary>• protected override void Dispose( bool disposing )• {• if( disposing )• {• if (components != null) • {• components.Dispose();• }• }• base.Dispose( disposing );• }
• #region Windows Form Designer generated code• /// <summary>• /// Required method for Designer support - do not modify• /// the contents of this method with the code editor.• /// </summary>• private void InitializeComponent()• {• this.label1 = new System.Windows.Forms.Label();• this.label2 = new System.Windows.Forms.Label();• this.label3 = new System.Windows.Forms.Label();• this.label4 = new System.Windows.Forms.Label();• this.label5 = new System.Windows.Forms.Label();• this.textBox1 = new System.Windows.Forms.TextBox();• this.textBox2 = new System.Windows.Forms.TextBox();• this.textBox3 = new System.Windows.Forms.TextBox();• this.textBox4 = new System.Windows.Forms.TextBox();• this.textBox5 = new System.Windows.Forms.TextBox();• this.panel1 = new System.Windows.Forms.Panel();• this.label6 = new System.Windows.Forms.Label();• this.label7 = new System.Windows.Forms.Label();• this.textBox6 = new System.Windows.Forms.TextBox();• this.SuspendLayout();
10
…• // configure components … • // • // panel1• //
• this.panel1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.panel1_MouseUp);
• this.panel1.MouseEnter += new System.EventHandler(this.panel1_MouseEnter);
• this.panel1.MouseHover += new System.EventHandler(this.panel1_MouseHover);
• this.panel1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.panel1_MouseMove);
• this.panel1.MouseLeave += new System.EventHandler(this.panel1_MouseLeave);
• this.panel1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panel1_MouseDown);
• // • // label6
• // configure components …• }• #endregion
• /// <summary>• /// The main entry point for the application.• /// </summary>• [STAThread]
• static void Main() • {• Application.Run(new Form1());• }
11
…• private void panel1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)• {• string s = textBox1.Text;• int temp = Convert.ToInt32(s);• temp +=1;• textBox1.Text = Convert.ToString(temp);• }
• private void panel1_MouseEnter(object sender, System.EventArgs e)• {• string s = textBox2.Text;• int temp = Convert.ToInt32(s);• temp +=1;• textBox2.Text = Convert.ToString(temp);• }
• private void panel1_MouseLeave(object sender, System.EventArgs e)• {• string s = textBox3.Text;• int temp = Convert.ToInt32(s);• temp +=1;• textBox3.Text = Convert.ToString(temp);• }
12
…/• private void panel1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)• {• string s = textBox4.Text;• int temp = Convert.ToInt32(s);• temp +=1;• textBox4.Text = Convert.ToString(temp);• }
• private void panel1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)• {• string s = textBox5.Text;• int temp = Convert.ToInt32(s);• temp +=1;• textBox5.Text = Convert.ToString(temp);
• }
• private void panel1_MouseHover(object sender, System.EventArgs e)• {• string s = textBox6.Text;• int temp = Convert.ToInt32(s);• temp +=1;• textBox6.Text = Convert.ToString(temp);
• }• }• }
13
Example (paint with mouse on Form)
A bit slower mouse motion
Slowest mouse motion
Hold the mouse down
and move … results in “painting”
Quick mouse motion
14
The code• using System;• using System.Drawing;• using System.Collections;• using System.ComponentModel;• using System.Windows.Forms;• using System.Data;
• namespace Painter• {• /// <summary>• /// creates a form as a drawing surface• /// </summary>• public class Painter : System.Windows.Forms.Form• {• bool shouldPaint = false; // whether to paint
• /// <summary>• /// Required designer variable.• /// </summary>• private System.ComponentModel.Container components = null;
• // default constructor• public Painter()• {• InitializeComponent();• }
•
15
…/// <summary>/// Clean up any resources being used./// </summary>protected override void Dispose( bool disposing ){
if ( disposing ){
if ( components != null ) {
components.Dispose();}
}
base.Dispose( disposing );}
#region Windows Form Designer generated codeprivate void InitializeComponent()
{// // Painter// this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);this.ClientSize = new System.Drawing.Size(352, 365);this.Name = "Painter";this.Text = "Painter";
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Painter_MouseDown);this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Painter_MouseUp);this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Painter_MouseMove);
} // end method InitializeComponent
/// <summary>/// The main entry point for the application./// </summary>[STAThread]
static void Main() {
Application.Run( new Painter() );}
16
…// should paint after mouse button has been pressedprivate void Painter_MouseDown(
object sender, System.Windows.Forms.MouseEventArgs e ){
shouldPaint = true;}
// stop painting when mouse button releasedprivate void Painter_MouseUp(
object sender, System.Windows.Forms.MouseEventArgs e ){
shouldPaint = false;}
// draw circle whenever mouse button // moves (and mouse is down)
protected void Painter_MouseMove( object sender, System.Windows.Forms.MouseEventArgs e )
{if ( shouldPaint ){
Graphics graphics = CreateGraphics();graphics.FillEllipse( new SolidBrush( Color.Red ), e.X, e.Y, 7, 7 );
}
} // end Painter_MouseMove
} // end class Painter
} // end namespace Painter
Graphics.FillEllipse Method : Fills the interior of an ellipse defined by a bounding rectangle. Fills the interior of an ellipse with a Brushobject. The ellipse is defined by the bounding rectangle specified by a pair of coordinates, a width, and a height.
SolidBrush Class:Defines a brush of a single color. Brushes are used to fill graphics shapes, such as rectangles, ellipses, pies, polygons, etc
17
Keyboard Event Handling• Key events
– Control that inherits from System.Windows.Forms.Control– Delegate KeyPressEventHandler
• Event argument KeyPressEventArgs• KeyPress
– ASCII character pressed– No modifier keys
– Delegate KeyEventHandler• Event argument KeyEventArgs• KeyUp or KeyDown
– Special modifier keys• Key enumeration value
18
Keyboard Event HandlingKeyboard Events, Delegates and Event Arguments
Key Events (Delegate KeyEventHandler, event arguments KeyEventArgs)
KeyDown Raised when key is initially pushed down. KeyUp Raised when key is released. Key Events (Delegate KeyPressEventHandler, event arguments KeyPressEventArgs)
KeyPress Raised when key is pressed. Occurs repeatedly while key is held down, at a rate specified by the operating system.
Class KeyPressEventArgs Properties
KeyChar Returns the ASCII character for the key pressed. Handled Whether or not the KeyPress event was handled. Class KeyEventArgs Properties Alt Indicates whether the Alt key was pressed. Control Indicates whether the Control key was pressed. Shift Indicates whether the Shift key was pressed. Handled Whether the event was handled. KeyCode Returns the key code for the key, as a Keys
enumeration. This does not include modifier key information. Used to test for a specific key.
KeyData Returns the key code as a Keys enumeration, combined with modifier information. Used to determine all information about the key pressed.
KeyValue Returns the key code as an int, rather than as a Keys enumeration. Used to obtain a numeric representation of the key pressed.
Modifiers Returns a Keys enumeration for any modifier keys pressed (Alt, Control and Shift). Used to determine modifier key information only.
Keyboard events, delegates and event arguments.
20
The code … • using System;• using System.Drawing;• using System.Collections;• using System.ComponentModel;• using System.Windows.Forms;• using System.Data;
• namespace WindowsApplication4_2Key• {• /// <summary>• /// Summary description for Form1.• /// </summary>• public class Form1 : System.Windows.Forms.Form• {• private System.Windows.Forms.Label label1;• private System.Windows.Forms.Label label2;•• /// <summary>• /// Required designer variable.• /// </summary>• private System.ComponentModel.Container components = null;
• public Form1()• {• //• // Required for Windows Form Designer support• //• InitializeComponent();
• //• // TODO: Add any constructor code after InitializeComponent call• //• }
21
…• /// <summary>• /// Clean up any resources being used.• /// </summary>• protected override void Dispose( bool disposing )• {• if( disposing )• {• if (components != null) • {• components.Dispose();• }• }• base.Dispose( disposing );• }
• #region Windows Form Designer generated code• /// <summary>• /// Required method for Designer support - do not modify• /// the contents of this method with the code editor.• /// </summary>• private void InitializeComponent()• {• this.label1 = new System.Windows.Forms.Label();• this.label2 = new System.Windows.Forms.Label();• this.SuspendLayout();• // configure components …• this.KeyDown += new
System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);• this.KeyUp += new
System.Windows.Forms.KeyEventHandler(this.Form1_KeyUp);• this.ResumeLayout(false);• }• #endregion• static void Main() • {• Application.Run(new Form1());• }
22
…/• private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)• {• label1.Text = label1.Text + e.KeyData ;• }
• private void Form1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)• {• label2.Text = label2.Text + e.KeyData ;• }
• }• }
23
Menus• Group related commands together• Contain:
– Commands– Submenus
• Exit uses Application class to quit
24
MenusMainMenu and MenuItem events and properties
Desc rip tion / Delegate and Event Arguments
MainMenu Properties MenuItems Collection of MenuItems for the MainMenu. RightToLeft Used to display text from right to left. Useful for languages that are
read from right to left.
MenuItem Properties Checked Whether menu item appears checked (according to property
RadioCheck). Default false, meaning that the menu item is not checked.
Index Item’s position in parent menu. MenuItems Collection of submenu items for this menu item.
25
Menus …MergeOrder This property sets the position of menu item when parent menu merged
with another menu.
MergeType This property takes a value of the MenuMerge enumeration. Specifies how parent menu merges with another menu. Possible values are Add, MergeItems, Remove and Replace.
RadioCheck If true, menu item appears as radio button (black circle) when checked; if false, menu item displays checkmark. Default false.
Shortcut Shortcut key for the menu item (i.e. Ctrl + F9 can be equivalent to clicking a specific item).
ShowShortcut If true, shortcut key shown beside menu item text. Default true. Text Text to appear on menu item. To make an Alt access shortcut, precede
a character with & (i.e. &File for File).
Common Events (Delegate EventHandler, event arguments EventArgs) Click Raised when item is clicked or shortcut key is used. Default when
double-clicked in designer.
Fig. 13.3 MainMenu and MenuItem p roperties and events.
26
Menus …Shortcut key
Disabled command
Separator bar
Menu
submenu
Checked menu item
Expanded and checked menus.
27
Menu designer form
Have created 2 menus, Options and Format
Have created 2 menu items, About and Exit.
32
using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.Windows.Forms;using System.Data;
namespace WindowsApplication4_3Menu{
/// <summary>/// Summary description for Form1./// </summary>public class Form1 : System.Windows.Forms.Form{
private System.Windows.Forms.MainMenu mainMenu1;private System.Windows.Forms.MenuItem menuItemOptions;private System.Windows.Forms.MenuItem menuItemFormat;private System.Windows.Forms.MenuItem menuItemAbout;private System.Windows.Forms.MenuItem menuItemExit;private System.Windows.Forms.MenuItem menuItemColor;private System.Windows.Forms.MenuItem menuItemColorRed;private System.Windows.Forms.MenuItem menuItemColorYello;private System.Windows.Forms.MenuItem menuItemColorBlue;/// <summary>/// Required designer variable./// </summary>private System.ComponentModel.Container components = null;
public Form1(){
//// Required for Windows Form Designer support//InitializeComponent();
//// TODO: Add any constructor code after InitializeComponent call//
}
The code …
33
…/// <summary>/// Clean up any resources being used./// </summary>protected override void Dispose( bool disposing ){
if( disposing ){
if (components != null) {
components.Dispose();}
}base.Dispose( disposing );
}
#region Windows Form Designer generated code/// <summary>/// Required method for Designer support - do not modify/// the contents of this method with the code editor./// </summary>
private void InitializeComponent(){
this.mainMenu1 = new System.Windows.Forms.MainMenu();this.menuItemOptions = new System.Windows.Forms.MenuItem();this.menuItemFormat = new System.Windows.Forms.MenuItem();this.menuItemAbout = new System.Windows.Forms.MenuItem();this.menuItemExit = new System.Windows.Forms.MenuItem();this.menuItemColor = new System.Windows.Forms.MenuItem();this.menuItemColorRed = new System.Windows.Forms.MenuItem();this.menuItemColorYello = new System.Windows.Forms.MenuItem();this.menuItemColorBlue = new System.Windows.Forms.MenuItem();// // mainMenu1//
// configure components …..// // menuItemAbout//
34
…this.menuItemAbout.Index = 0;this.menuItemAbout.Text = "About";
this.menuItemAbout.Click += new System.EventHandler(this.menuItemAbout_Click);//…this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click);//…this.menuItemColorRed.Click += new System.EventHandler(this.menuItemColorRed_Click);//…this.menuItemColorYello.Click += new System.EventHandler(this.menuItemColorYello_Click);//…this.menuItemColorBlue.Click += new System.EventHandler(this.menuItemColorBlue_Click);//…
[STAThread]static void Main() {
Application.Run(new Form1());}
35
…/private void menuItemAbout_Click(object sender, System.EventArgs e){
MessageBox.Show("You are using a GUI with menus");}
private void menuItemExit_Click(object sender, System.EventArgs e){
this.Close();}
private void menuItemColorRed_Click(object sender, System.EventArgs e){
this.BackColor = Color.Red;}
private void menuItemColorYello_Click(object sender, System.EventArgs e){
this.BackColor = Color.Yellow;}
private void menuItemColorBlue_Click(object sender, System.EventArgs e){
this.BackColor = Color.Blue;}
}}
36
LinkLabels
• Displays links to other objects– Uses event handlers to link to right file or
program– Start method of Process class opens other
programs• Derived from class Label, inherits
functionality
37
LinkLabelsLinkLabel p ro p e rt ie s a n d e v e n ts
D e sc rip t io n / D e le g a te a n d Ev e n t A rg u m e n ts
C om m on Properties
ActiveLinkColor Specifies the color o f the active link w hen clicked. D efault is red. LinkArea Specifies w hich portion of text in the LinkLabel is treated as part of
the link. LinkBehavior Specifies the link’s behavior, such as how the link appears w hen the
m ouse is placed over it.
LinkColor Specifies the origina l color of a ll links before they have been vis ited. D efault is blue.
Links Lists the LinkLabel.Link objects, w hich are the links conta ined in the LinkLabel .
LinkVisited If True , link appears as if it w ere visited (its color is changed to that specified by property VisitedLinkColor ). D efault False .
Text Specifies the text to appear on the contro l. UseMnemonic If True , & character in Text property acts as a shortcut (s im ilar to
the Alt shortcut in menus). VisitedLinkColor Specifies the color o f vis ited links. D efault is Color.Purple . C om m on Event (D elegate LinkLabelLinkClickedEventHandler , event
argum ents LinkLabelLinkClickedEventArgs )
LinkClicked G enerated w hen link is clicked. D efault w hen contro l is double-clicked in designer.
38
Example
Clicking the label will open the appropriate link
(start appropriate process).. Hand icon is displayed when mouse
is on top of the link label.
41
The code …using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.Windows.Forms;using System.Data;
namespace WindowsApplication4_4LinkLabel{
/// <summary>/// Summary description for Form1./// </summary>public class Form1 : System.Windows.Forms.Form{
private System.Windows.Forms.LinkLabel linkLabel1;private System.Windows.Forms.LinkLabel linkLabel2;private System.Windows.Forms.LinkLabel linkLabel3;private System.Windows.Forms.LinkLabel linkLabel4;/// <summary>/// Required designer variable./// </summary>private System.ComponentModel.Container components = null;
public Form1(){
//// Required for Windows Form Designer support//InitializeComponent();
//// TODO: Add any constructor code after InitializeComponent call//
}
//…
42
…private void InitializeComponent(){
this.linkLabel1 = new System.Windows.Forms.LinkLabel();this.linkLabel2 = new System.Windows.Forms.LinkLabel();this.linkLabel3 = new System.Windows.Forms.LinkLabel();this.linkLabel4 = new System.Windows.Forms.LinkLabel();
//…this.linkLabel1.LinkClicked += new
System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);//…
this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked);
//…this.linkLabel3.LinkClicked += new
System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel3_LinkClicked);//…
this.linkLabel4.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel4_LinkClicked);
//…
}static void Main() {
Application.Run(new Form1());}
43
…/private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{System.Diagnostics.Process.Start("IExplore",
"http://www.yorku.ca/anestis");}
private void linkLabel2_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{System.Diagnostics.Process.Start("WinWord.exe");
}
private void linkLabel3_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{System.Diagnostics.Process.Start("TextPad.exe");
}
private void linkLabel4_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{System.Diagnostics.Process.Start("cmd");
}}
}
Start internet explorer and go to a specified site.
Start Microsoft Word
Start TextPad
Open a DOS box
45
ListBoxes and CheckedListBoxes
• ListBoxes– Allow users to view and select from items on a list– Static objects– SelectionMode property determines number of items that can be selected– Property Items returns all objects in list– Property SelectedItem returns current selected item– Property SelectedIndex returns index of selected item– Property GetSelected returns true if property at given index is selected– Use Add method to add to Items collection
• myListBox.Items.Add(“myListItem”)• CheckedListBoxes
– Extends ListBox by placing check boxes next to items– Can select more than one object at one time