Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Lect Note On Chapter 3 - Part II - Event-Driven Component

Uploaded by

beshahashenafi32
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Lect Note On Chapter 3 - Part II - Event-Driven Component

Uploaded by

beshahashenafi32
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 73

GUI - components

Menus
LinkLabels
ListBoxes and CheckedListBoxes
ComboBoxes
TreeViews
ListViews
Tab Control
Multiple-Document-Interface (MDI) Windows
Common dialog
Menus
• Menus are used to provide groups of related commands for Windows
applications.
• An expanded menu lists various commands (called menu items), plus
submenus (menus within a menu).
• top-level menus appear in the left portion of the figure, whereas any
submenus or menu items are displayed to the right.
• The menu that contains a menu item is called parent menu.
• A menu item that contains a submenu is considered to be the parent of that
submenu.
• All menu items can have Alt key shortcuts (also called access shortcuts or hot
keys),
– accessed by pressing Alt and the underlined letter (for example, Alt + F retrieves the
File menu).
• Menus that are not top-level menus can have shortcut keys as well
(combinations of Ctrl, Shift, Alt, F1, F2, letter keys etc.).
• Some menu items display checkmarks, usually indicating that multiple
options on the menu can be selected at once.
• To create a menu, open the Toolbox, and drag a MainMenu
control onto the form.
• This creates a menu bar on the top of the form and places a
MainMenu icon underneath it.
• To select the MainMenu, click the icon. This setup is known
as the Visual Studio .NET Menu Designer, which allows the
user to create and edit menus.
• Menu have properties, which can be accessed through the
Properties window or the Menu Designer, and events, which
can be accessed through the Class Name and Method Name
drop-down menus.
• To add entries to the menu – click Type Here textbox and type the text that should appear in
the menu.
• Each entry in the menu is of type MenuItem from the System.Windows.Forms namespace.
The menu itself is of type MainMenu.
• Pressing the Enter key, add the menu item.
• Then, more Type Here textboxes appear, allowing us to add items underneath or to the side
of the original menu item.
• To create an access shortcut - type an ampersand (&) in front of the character to be
underlined.
– E.g. to create the File menu item, type &File.
• The actual ampersand character is displayed by typing &&.
• To add other shortcut keys (such as Ctrl + F9), set the Shortcut property of the MenuItem.
• Programmers can remove a menu item by selecting it with the mouse and pressing the Delete
key.
• Separator bars are inserted by right-clicking the menu and selecting Insert Separator or by
typing “-” as the menu text.
• Menu items generate a Click event when selected.
• To create an empty event handler, enter code-view mode, double click on the MenuItem in
design view.
• Menus can also display the names of open windows in multiple-document-interface (MDI)
forms (see Section 13.9). Menu properties and events are summarized in Fig. 13.3.
LinkLabels
• Class LinkLabel is derived from class Label and
therefore inherits all of class Label’s
functionality.
• The LinkLabel control displays links to other
objects, such as files or Web pages.
• A LinkLabel appears as underlined text (colored
blue by default).
• similar to the behavior of a hyperlink in a Web
page.
• When clicked, the LinkLabel generates a
LinkClicked event.
• The event handlers for the LinkLabel instances call static method Start of
class Process (namespace System.Diagnostics).
– This method allows us to execute other programs from our application.
– Method Start can take as arguments either the file to open (a String) or the
name of the application to run and its command-line arguments (two Strings).
– Method Start’s arguments can be in the same form as if they were provided
for input to the Run command in Windows.
– To open a file that has a file type that Windows recognizes, simply insert the
file’s full path name.
– The Windows operating system should be able to use the application
associated with the given file’s extension to open the file.
• Demo – the following application contains three
linklabels to link to the:
– C:\drive, the yahoo mail page (www.mail.yahoo.com) and
the Notepad application, respectively.
– The Text properties of the LinkLabels:
driveLinkLabel, yahooLinkLabel and
notepadLinkLabel are set to describe each link’s
purpose
// browse C:\ drive
private void driveLinkLabel_LinkClicked( object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs
e)
{
driveLinkLabel.LinkVisited = true;
System.Diagnostics.Process.Start( "C:\\" );
}

// load www.mail.yahoo.com in Web broswer


private void yahooMailLinkLabel_LinkClicked( object sender,
System.Windows.Forms.LinkLabelLinkClickedEventArgs e )
{
yahooMailLinkLabel.LinkVisited = true;
System.Diagnostics.Process.Start("IExplore", "https://www.yahoo.com");
}

// run application Notepad


private void notepadLinkLabel_LinkClicked( object sender,
System.Windows.Forms.LinkLabelLinkClickedEventArgs e )
{
notepadLinkLabel.LinkVisited = true;

// program called as if in run


// menu and full path not needed
System.Diagnostics.Process.Start( "notepad”);
}
• The event handler for driveLinkLabel’s LinkClicked events browses the C:\ drive.
– sets the LinkVisited property to True – (to changes the link’s color) from blue to
purple.
– The event handler then passes "C:\" to method Start - to opens a Windows Explorer
window.
• The event handler for LinkLabel’s LinkClicked events opens the Web page
www.mail.yahoo.com in Internet Explorer.
– Pass the string "IExplore" and the Web-page address, which opens Internet Explorer.
– sets the LinkVisited property to True.
• The event handler for notepadLinkLabel’s LinkClicked events opens the
specified Notepad application
– sets the link to appear as a visited link.
– passes the argument "notepad" to method Start, which calls
notepad.exe (.exe extension is not required—Windows can determine
whether) the argument given to method Start is an executable file.
ListBoxes and CheckedListBoxes
• ListBox control - allows the user to view and select from
multiple items in a list.
• ListBoxes are static GUI entities - users cannot enter new
items in the list.
• The CheckedListBox control extends a ListBox by including
check boxes next to each item in the list.
– allows users to place checks on multiple items at once
• Both ListBox and CheckedListBox – contain scroll bars if the
number of items is too large to be displayed simultaneously in
the component.
Common property
• SelectionMode property determines the
number of items that can be selected.
– possible values None, One, MultiSimple and
MultiExtended (from SelectionMode
enumeration)
• The SelectedIndexChanged event occurs
when the user selects a new item.
• Both the ListBox and CheckedListBox have properties Items,
SelectedItem and SelectedIndex.
• Property Items returns all the objects in the list as a collection.
(Collections are a common way of exposing lists of Objects in the .NET
framework. )
• Many .NET GUI components (e.g., ListBoxes) use collections to expose
lists of internal objects (e.g., items contained within a ListBox).
• Property SelectedItem returns the currently selected item. If the user
can select multiple items, use collection SelectedItems to return all
the selected items as a collection.
• Property SelectedIndex returns the index of the selected item—if
there could be more than one, use property SelectedIndices.
– If no items are selected, property SelectedIndex returns -1.
• Method GetSelected takes an index and returns True if the
corresponding item is selected.
• Two alternative to add items to ListBox/ CheckedListBox.
• Programmatically, to add items to the ListBox or the CheckedListBox -
you must add objects to its Items collection.
– accomplished by invoking method Add to add a String to the Items collection.
– myListBox.Items.Add( "myListItem" )
//add String myListItem to ListBox myListBox.
• To add multiple objects - use method use method AddRange to add an
array of objects.
• Both ListBox and CheckedListBox use ToString method to determine the
label for the corresponding object’s entry in the list.
• Visually, add items to ListBoxes and CheckedListBoxes visually by
examining the Items property in the Properties window.
• Clicking the ellipsis opens the String Collection Editor, a text area in
which we can type the items to add; each item should appear on a
separate line.
• Visual Studio .NET then adds these Strings to the Items collection inside
method InitializeComponent.
ListBoxes
• Demo. the following program enables the user to add, remove and clear items
from ListBox displayListBox (see the next slid).
– The program uses TextBox input - to allow the user to type in a new item.
– When the user clicks button addButton - the new item appears in displayListBox.
– Similarly, if the user selects an item and clicks removeButton - the item is deleted.
– Control clear Button - deletes all entries in displayListBox.
– exitButton - allow the user to terminates the application.
• Description of each event handler
• addButton_Click event handler
– calls method Add of the Items collection, which takes a String as the item to add to ListBox. The
String used is the user-input text (or inputTextBox.Text)
– After the item is added, inputTextBox.Text is cleared.
private void addButton_Click( object sender, System.EventArgs e )
{
// add new item (from input box) and clear input box
displayListBox.Items.Add( inputTextBox.Text );
inputTextBox.Clear();
}
• removeButton_Click event handler calls method Remove of the Items collection.
– first uses property SelectedIndex to check which index is selected.

– Unless SelectedIndex is -1 , the handler removes the item of the selected index.
private void removeButton_Click( object sender, System.EventArgs e ) // remove item if one selected
{
// remove only if item selected
if ( displayListBox.SelectedIndex != -1 )
displayListBox.Items.RemoveAt(displayListBox.SelectedIndex );
}

• clearButton_Click event handler calls method Clear of the Items collection.


– This removes all the entries in displayListBox.
private void clearButton_Click(object sender, System.EventArgs e ) //clear all items

{
displayListBox.Items.Clear();
}

• Finally, event handler exitButton_Click terminates the application, using method Application.Exit.
private void exitButton_Click( object sender, System.EventArgs e ) //exit application

{
Application.Exit();

}
CheckedListBoxes
• CheckedListBox control derives from class ListBox and includes a
checkbox.
• As in ListBoxes, items can be added via methods Add and AddRange or
through the String Collection Editor.
• CheckedListBoxes imply that multiple items can be selected,
– possible values for the SelectionMode property are SelectionMode.None and
SelectionMode.One.
• SelectionMode.One allows multiple selection,
• Thus, the only choice is whether to give the user multiple selection or no
selection at all.
• This keeps the CheckedListBox’s behavior consistent with that of
CheckBoxes.
• The programmer is unable to set the last two SelectionMode values,
MultiSimple and MultiExtended, because the only logical selection
modes are handled by None and One.
• Common properties and events of CheckedListBoxes appear in Fig.
13.12.
• Event ItemCheck is generated whenever a user checks or
unchecks a CheckedListBox item.
• Event argument properties CurrentValue and NewValue
return CheckState values for the current and the new state
of the item, respectively.
• A comparison of these values allows us to determine
whether the CheckedListBox item was checked or
unchecked.
• The CheckedListBox control retains the SelectedItems and
SelectedIndices properties (inherits from class ListBox).
• However, it also includes properties CheckedItems and
CheckedIndices, which return information about the
checked items and indices.
• The following example uses a CheckedListBox and a
ListBox to display a user’s selection of books.
• The CheckedListBox named inputCheckedListBox
allows the user to select multiple titles.
• Using String Collection Editor add the following items:
– C++, Java, VB, Internet & WWW, Perl, Python, Wireless
Internet and Advanced Java.
• The ListBox, named displayListBox – displays the
user’s selection.
• In the screen shots accompanying this example, the
CheckedListBox appears to the left, the ListBox to the
right.
• When the user checks or unchecks an item in
CheckedListBox inputCheckedListBox, the system generates
an ItemCheck event.
• Event handler inputCheckedListBox_ItemCheck handles
the event.
• An if/else control structure determines whether the user
checked or unchecked an item in the CheckedListBox.
• The program uses the NewValue property to test for
whether the item is being checked (CheckState.Checked).
• If the user checks an item, adds the checked entry to the
ListBox displayListBox.
• If the user unchecks an item, line 41 removes the
corresponding item from displayListBox.
// item about to change, add or remove from displayListBox
private void inputCheckedListBox_ItemCheck( object sender,
System.Windows.Forms.ItemCheckEventArgs e )
{
// obtain reference of selected item
string item = inputCheckedListBox.SelectedItem.ToString();
// if item checked add to listbox otherwise remove from listbox
if ( e.NewValue == CheckState.Checked )
displayListBox.Items.Add( item );
else
displayListBox.Items.Remove( item );
}
ComboBoxes
• ComboBox control - combines TextBox features with a
drop-down list.
• A drop-down list is a GUI component that contains a list
from which values can be chosen.
• It usually appears as a text box with a down arrow to its
right.
• By default, the user can enter text into the text box or
click the down arrow to display a list of predefined items.
• If a user chooses an element from this list, that element is
displayed in the text box.
• The maximum number of items that a drop-down list can
display at one time is set by property
MaxDropDownItems.
sample ComboBox in three different states.
• You can add objects to collection Items
programmatically, using methods Add and
AddRange, or visually, with the String
Collection Editor.
• Class ComboBoxTest (Fig. 13.16) allows users
to select a shape to draw—an empty or filled
circle, ellipse, square or pie—by using a
ComboBox.
• The combo box in this example is uneditable,
so the user cannot input a custom item.
• Add items Circle, Square, Ellipse, Pie, Filled
Circle, Filled Square, Filled Ellipse and Filled
Pie to the Items collection.
• Whenever the user selects an item from imageComboBox, the
system generates a SelectedIndexChanged event.
• Event handler imageComboBox_SelectedIndexChanged handles
these events.
• create a Graphics object, a Pen and a SolidBrush, with which the
program draws on the form.
• The Graphics object allows a pen or brush to draw on a
component, using one of several Graphics methods.
• The Pen object is used by methods drawEllipse, drawRectangle
and drawPie to draw the outlines of their corresponding shapes.
• The SolidBrush object is used by methods fillEllipse, fillRectangle
and fillPie to draw their corresponding solid shapes.
• Colors the entire form White, using Graphics method Clear.
// create graphics object, pen and brush
Graphics myGraphics = base.CreateGraphics();

// create Pen using color DarkRed


Pen myPen = new Pen( Color.DarkRed );

// create SolidBrush using color DarkRed


SolidBrush mySolidBrush =new SolidBrush( Color.DarkRed );

// clear drawing area setting it to color White


myGraphics.Clear( Color.White );
TreeViews
• TreeView controls are useful for displaying hierarchal information, such as
the file structure.
• It displays nodes hierarchically on a tree.
• Traditionally, nodes are objects that contain values and can refer to other
nodes.
• A parent node contains child nodes, and the child nodes can be parents to
other nodes.
• Two child nodes that have the same parent node are considered sibling
nodes.
• A tree is a collection of nodes, usually organized in a hierarchical manner.
• The first parent node of a tree is the root node (a TreeView can have
multiple roots).
– For example, the file system of a computer can be represented as a tree.
• The top-level directory (perhaps C:) would be the root, each subfolder of C:
would be a child node and each child folder could have its own children.
• A parent node can be expanded or collapsed by clicking the plus or minus
box to its left.
• The nodes displayed in a TreeView are instances of class TreeNode.
• Each TreeNode has a Nodes collection (type TreeNodeCollection), which
contains a list of other TreeNodes—its children.
• The Parent property returns a reference to the parent node (or null if the node
is a root node).
• list the common properties of TreeViews and TreeNodes and an event of
TreeViews.
• To add nodes to the TreeView visually,
– click the ellipsis by the Nodes property in the Properties window.
– This opens the TreeNode Editor, which displays an empty tree representing the
TreeView (Fig. 13.20).
– There are buttons to create a root, to add or delete a node.
• Adding nodes throgh programm writing
– First create a root node.
– Make a new TreeNode object and pass it a String to display.
– Then, use method Add to add this new TreeNode to the TreeView’s Nodes collection.
– E.g. add a root node to TreeView myTreeView, write
myTreeView.Nodes.Add(New TreeNode(RootLabel));
• where myTreeView is the TreeView to which we are adding
nodes, and RootLabel is the text to display in myTreeView.
• To add children to a root node, add new TreeNodes to its
Nodes collection.
• We select the appropriate root node from the TreeView by
writing
– myTreeView.Nodes(myIndex)
• where myIndex is the root node’s index in myTreeView’s
Nodes collection.
• We add nodes to child nodes through the same process by
which we added root nodes to myTreeView.
• To add a child to the root node at index myIndex, write
– myTreeView.Nodes(myIndex).Nodes.Add(New TreeNode(ChildLabel))
public void PopulateTreeView( string directoryValue, TreeNode parentNode )
{
// populate current node with subdirectories
string[] directoryArray = Directory.GetDirectories( directoryValue );
// populate current node with subdirectories
try
{
if ( directoryArray.Length != 0 )
{
// for every subdirectory, create new TreeNode, add as child of current node and recursively populate child
nodes with subdirectories
foreach ( string directory in directoryArray )
{
TreeNode myNode = new TreeNode( directory ); // create TreeNode for current directory
parentNode.Nodes.Add( myNode ); // add current directory node to parent node

PopulateTreeView( directory, myNode ); // recursively populate every subdirectory


}
} // end if
}
catch ( UnauthorizedAccessException ) // catch exception
{
parentNode.Nodes.Add( "Access denied" );
}
} // end PopulateTreeView
// called by system when form loads
private void TreeViewDirectoryStructureTest_Load(object sender, System.EventArgs e)
{
// add c:\ drive to directoryTreeView and insert its subfolders
directoryTreeView.Nodes.Add( "C:\\" );
PopulateTreeView("C:\\", directoryTreeView.Nodes[ 0 ] );
}
• Method PopulateTreeView (lines 25–61) obtains a list of
subdirectories, using method GetDirectories of class
Directory (namespace System.IO) on lines 29–30.
• Method GetDirectories takes a String (the current directory)
and returns an array of Strings (the subdirectories).
• If a directory is not accessible for security reasons, an
UnauthorizedAccessException is thrown.
• Lines 56–59 catch this exception and add a node containing
“Access Denied” instead of displaying the subdirectories.
Tab Control
• The TabControl control creates tabbed windows, such as those we have seen in
the Visual Studio .NET IDE (Fig. 13.25).
• This allows the programmer to design user interfaces that fit a large number of
controls or a large amount of data without using up valuable screen “real estate.”
• TabControls contain TabPage objects, which are similar to Panels and
GroupBoxes in that TabPages also can contain controls.
• The programmer first adds controls to the TabPage objects, then adds the
TabPages to the TabControl.
• Only one TabPage is displayed at a time. Figure 13.26 depicts a sample
TabControl.
• Programmers can add TabControls visually by dragging and dropping them onto
a form in design mode.
• To add TabPages in the Visual Studio .NET designer, right-click the TabControl,
and select Add Tab (Fig. 13.27).
• Alternatively, click the TabPages collection in the Properties window, and add
tabs in the dialog that appears.
• To change a tab label, set the Text property of the TabPage.
• Note that clicking the tabs selects the
TabControl—to select the TabPage, click the
control area underneath the tabs.
• The developer can add controls to the
TabPage by dragging and dropping items from
the ToolBox.
• To view different TabPages, click the
appropriate tab (in either design or run
mode).
• Common properties and events of
TabControls are described in Fig. 13.28.
Multiple-Document-Interface (MDI) Windows
• Two type of application: SDI vs. MDI
• Single-document-interface (SDI) applications (all built before)
– E.g. Notepad or Paint – support one open window/ document at a
time.
– To edit multiple documents, the user must create additional instances
of the SDI application.
• Multiple document interface (MDI) programs (such as PaintShop
Pro and Adobe Photoshop) enable users to edit multiple
documents at once.
• MDI programs also tend to be more complex—PaintShop Pro
and Photoshop have a greater number of image-editing features
than does Paint.
• Until now, the applications we created were SDI applications.
• We define this here to emphasize the distinction between the
two types of programs.
• The application window of an MDI program is called the parent
window, and each
• window inside the application is referred to as a child window.
• MDI application can have many child windows, but each has
only one parent window.
• A maximum of one child window can be active at once.
• Child windows cannot be parents themselves and cannot be
moved outside their parent.
• A child window behaves like any other window (with regard to
closing, minimizing, resizing etc.).
• A child window’s functionality can be different from other child
windows of the parent.
– E.g. one child window - edit images, another - edit text and a third -
display network traffic graphically, but all belong to same MDI parent.
• To create an MDI form,
– create a new Form and
– set its IsMDIContainer property to True.
• Next, create a child form class to be added to the form.
– right-click the project in the Solution Explorer, select Add Windows Form... and
name the file.
• To add the child form to the parent
– create a new child form object (e.g Child cldFrm = new Child(););
– cldFrm.MdiParent = this; //Then, set its MdiParent property to the parent form, and
– cldFrm.show();//call method Show.
• The code to create a child usually lies inside an event handler, which creates a
new window in response to a user action.
• Menu selections (such as File followed by a submenu option of New followed
by a submenu option of Window) are common methods of creating new child
windows.
• Form property MdiChildren is an array of child Form references.
• This is useful if the parent window wants to check the status of all its children
(such as to ensure that all are saved before the parent closes).
• Property ActiveMdiChild returns a reference to the active child window; it
returns null if there are no active child windows.
• Child windows can be minimized, maximized and closed independently of each other and of
the parent window.
• child windows and a second containing a maximized child window.
• When the parent is minimized or closed, the child windows are minimized or closed as well.
• Notice that the title bar in the second image is Parent Window - [Child].
• When a child window is maximized, its title bar is inserted into the parent window’s title bar.
• When a child window is minimized or maximized, its title bar displays a restore icon, which
returns the child window to its previous size (its size before it was minimized or maximized).
• Parent and child forms - can have different menus,
which are merged whenever a child window is selected.
• To specify how the menus merge,
– set the MergeOrder and the MergeType properties for each
MenuItem.
• MergeOrder determines the order in which MenuItems
appear when two menus are merged.
• MenuItems with a lower MergeOrder value will
appear first.
– E.g. if Menu1 has items File, Edit and Window (and their orders are 0, 10 and
20) and Menu2 has items Format and View (and their orders are 7 and 15), then
the merged menu contains menu items File, Format, Edit, View and Window, in
that order.
• MDI containers allow to organize the placement of child windows.
• The child windows arranged by calling method LayoutMdi of the
parent form.
• Method LayoutMdi takes a LayoutMdi enumeration,
– of values ArrangeIcons, Cascade, TileHorizontal and TileVertical.
• Tiled windows completely fill the parent and do not overlap; such
windows can be arranged horizontally (value TileHorizontal) or
vertically (value TileVertical).
• Cascaded windows (value Cascade) overlap—each is the same size
and displays a visible title bar, if possible.
• Value ArrangeIcons arranges the icons for any minimized child
windows.
• If minimized windows are scattered around the parent window,
value ArrangeIcons orders them neatly at the bottom-left corner of
the parent window.
Arrange option of MDI child windows
• this.LayoutMdi( MdiLayout.Cascade );
• this.LayoutMdi( MdiLayout.TileHorizontal );
Common dialog boxes
• Common dialog boxes: Windows Forms provides several
canned dialog boxes for common operations (e.g.,
ColorDialog, SaveFilesDialog, OpenFileDialog, PrintDialog, and
ColorDialog).
• As you would hope, you can certainly build your own custom
dialog boxes if the standard dialog boxes do not suit your
needs.
OpenFileDialog

• // Create an open file dialog box and only show text


files.
OpenFileDialog openDlg = new OpenFileDialog();
openDlg.Filter = "Text Files |*.txt";
// Did they click on the OK button?
if (true == openDlg.ShowDialog())
{
// Load all text of selected file.
string dataFromFile = File.ReadAllText(openDlg.FileName);
// Show string in TextBox.
txtData.Text = dataFromFile;
}
SaveFileDialog
• Save the data in text box to named file
SaveFileDialog saveDlg = new SaveFileDialog();
saveDlg.Filter = "Text Files |*.txt";
// Did they click on the OK button?
if (DialogResult.Ok == saveDlg.ShowDialog())
{
// Save data in the TextBox to the named file.
File.WriteAllText(saveDlg.FileName, txtData.Text);
}
• ColorDialog - Create and display color dialog, and
ColorDialog dlg = new ColorDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
frm = dlg.Color;
}
• FolderBrowserDialog
FolderBrowserDialog fldDlg = new FolderBrowserDialog();
if(fldDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK);
{
System.Diagnostics.Process.Start(fldDlg.SelectedPath);

You might also like