Chapter 3a
Chapter 3a
Menu
Creating Menus in Your Programs
Adding Sub menus
Adding Shortcuts to your Menu Items
Adding Check mark
Adding Images
Creating ToolBar
Adding Code to Menus
The Open File Dialogue Box
The Save File Dialog Control
Cut, Copy, Paste and Undo in C# .NET…
Generic Ways to cut, copy, paste and undo … menus
How to Show and Hide Controls
2
A menu is a list of actions that can be performed on a program.
Image
3
In this section we’ll see how to add menus to a
C#.NET form.
Start a new project.
To your new form, use the toolbox to add a
MenuStrip control (from Menus & Toolbars)
Double click the control to add one to your form.
you'll notice two things.
At the top
At the bottom
4
• The component added at the bottom is the control itself.
• If you click on this component, you'll see that the Properties box for
the control menustrip.
• And there are lots of properties for the MenuItem object.
• The MenuItem object is the one at the top of the form
• To create a menu you may create your own from scratch or add
standard menu items.
• To add standard menu items
• Right-click the MenuStrip1 control on the form
• Select the Insert Standard Items context menu item to have the
standard menu items automatically inserted.
5
To start building your menu from the scratch, click inside the area that
says "Type Here". Type the word File:
To create items on your File menu, click inside the Type Here box.
Enter the word New, and press the enter key on your keyboard again.
Add an "Open" and a "Save" item to your menu in the same way.
6
• The final item we'll add to our menu is an “Quit" item.
• Before Quit is added lets put a separator between the "Save" and
"Quit".
• To add a separator, click inside the blue "Type Here" box.
• Instead of typing a letter, type the minus character "-”
• When you hit your return key, you'll see the separator appear
Click inside the "Type Here" area, and add an Quit item.
Click back on your form, away from the menu, to finish off.
7
• A sub menu is one that branches of a menu item.
• They usually have an arrow to indicate that there's an extra menu
available.
• To create submenu for New menu item
Click on your File menu so that you can see it all
Select the New item (Careful where you click. Click once on the left
edge
Click on the "Type Here" just to the right of New
Type New Project, and then hit the return key on your keyboard
Type in New File and then click away from the menu, somewhere on
the form
You will then have two sub menus added
8
• There's two types of shortcuts:
– An underline shortcut (Access Keys)
– A key combination shortcut (Shortcut keys)
• To add an underline shortcut(Access Keys)
Click on your New menu item once. This will select it
Position your cursor before the "N" of New
Type an ampersand symbol (&). Hit the return key on your keyboard
Notice that "N" of New is now underlined.
If you want an underline shortcut, the ampersand character should be
typed before the letter you want underlined.
Hold down the Alt key while your program is running to be able to see
the underlines
9
Key combination shortcuts
A key combination shortcut is one that appears at the end of a menu
item (Ctrl + U, for example). .
To add Key combination shortcuts
In Design time, select the Quit item on your menu
Look at the properties box on the right
Locate the ShortcutKeys item:
Click the down arrow to
reveal the following:
10
The Modifier is the key you press with your shortcut.
For example, the CTRL key then the “U" key on your
keyboard.
Place a check inside the Ctrl box.
Then select the letter “u" from the Key dropdown list
Click back on your menu to see what it looks like
11
To add a check mark to sub menus
set the checked property of the sub
menu to true.
By default it is false.
For New File submenu checked
property is set to true, That is why,
as shown on the figure, a check
mark precedes the sub menu
12
To add an image to a menu item or a sub menu use the image
property of the menu item or sub menu.
Click on the three dots next to the property.
You get an interface that asks you to import the image – locate
and import the image.
13
Menus and its associated menu items as well as sub menus can be
added using Items property of MenuStrip Control.
Lets create an Edit menu and its sub menus using this method.
Select MenuStrip Control (just click on it once)
Choose the Items property and click on the three dots next to it
Items Collection Editor will appear – while MenuStrip is selected
click on Add button.
A new member with default name ToolStripMenu1 will appear.
Type &Edit as a value for its Text property.You can also change other
properties like the Name property.
Add Sub Menus using DropDownItems Property.
When you choose the DropDownItems property three dots will
14 appear - click on them.
Another Items Collection Editor will appear.
From this window you can add sub menus and change their
properties.
15
• Add the following Menu item to the menu bar you have already
designed
16
In this section, you add the toolbars and buttons for the toolbars that
the application needs.
The menus created in the previous section will control the displaying
and hiding of these toolbars.
To Add ToolBars
Return to the Forms Designer in your Windows Forms Menus project.
You need to add two toolbars to the form, so locate the ToolStrip control
in the Toolbox and drag and drop it on your form; it automatically aligns
itself to the top of the form below the menu.
If you want to add default toolbar buttons, so right-click the ToolStrip
control on the form and select Insert Standard Items from the context
menu to have the standard toolbar buttons added.
17
Next, add a second toolbar to the form in the same manner. It
aligns itself below the first toolbar.
Lets add three buttons to this toolbar, so
click the ellipsis dots button next to the Items property in the
Properties window or
right-click the ToolStrip control on the form and select Edit
Items from the context menu.
In the Items Collection Editor dialog box, click the Add button
to add the first button
You can accept the default name and ToolTip text for these
buttons.
Ensure the DisplayStyle property is set to Image, and then
click the ellipsis dots button next to the Image property.
18
In the Select Resource dialog box, click the Import button and
browse to location of an image to be displayed on the toolbar and
import it.
Add the other two buttons in the same way.
You can use the tool strip added at the top to add tools on a tool
bars
19
In preceding slides we have seen how to add menus and
toolbars
In this section, we'll write code so that your menu items
actually do something.
In other words,
the Edit > Cut menu will really cut text, and
the Edit > Paste menu will really paste text.
Click File in Design Time to see your drop down menu.
You can double click an item to open up the code window. Or:
Press F7 on your keyboard to go to the code window.
20
The Quit menu here is "QuitToolStripMenuItem".
If you were to click that item, a code stub would open, ready for
you to type your code.
However, “QuitToolStripMenuItem" is very difficult to
remember. We can rename our menu items so that they are
more descriptive. So do the following
• Get back to your form by pressing Shift + F7 on your keyboard
• Click the File menu to select it
• Select your Quit item.
• When you have the Quit item selected, look at the properties box on
the right – its Name property has value mnuFileQuit.
21
• Press your return key on your keyboard to confirm the change
Now press F7 again to bring the code window up.
Or select the Quite sub menu and select the events icon from properties
windowdouble click the click event of the sub menuIt will take you
automatically to the code window of the sub menu.
private void mnuFileQuite_Click(object sender, EventArgs e)
{
this.Close();//your code here
}
• this –refers to the current form
• To test out your new code, run your program.
– Click your File menu, and then click the Quit item.
– Your form should close down, and you'll be returned to the design
22 environment.
Common dialog class
23
• In most programs, if you click the File menu, and select the Open
item, a dialogue box is displayed.
• From the dialogue box, you can click on a file to select it, then click
the Open button.
• The file you clicked on is then opened up. We'll see how to do that
from our menu.
– Except, the file won't open yet - only the dialogue box will display, and
then name of the chosen file.
Open up your toolbox, and locate the control called
"OpenFileDialog“ from Dialog tool category. Double click the
control to add one to your project.
But notice that the control doesn't get added to your form. It gets
24 added to the area at the bottom, next to your menu control:
• Change the Name property to OFDialog. When you change the name
in the properties box, the name of the control at the bottom will
change:
• Lets add a code to manipulate the properties of our new control.
– Access the code for your File > Open menu item.
– Goto the properties windowclick on the events icon
– Then select the Click event from the drop down box to the right
– With you cursor flashing between the two lines of your code, add the
following: OFDialog.ShowDialog();
• This method of the OpenFileDialog control does what you'd expect it
to do: Shows the dialogue box.
25
• The Initial Directory: You can set which directory the dialogue box
should display when it appears.
– This done with the Initial Directory property.
OFDialog.InitialDirectory = "C:\\“;
• The Title Property: By default, the dialogue box will display the
word "Open" as a caption at the top of your dialogue box(on the
title bar).
– You can change this with the Title property
OFDialog.Title = "Open a Text File“;
The Filter Property: In most dialogue boxes, you can display a list of
specific files that can be opened.
These are displayed in the "Files of Type" drop down list.
26
• To restrict our users to only opening Text files, those that end in the
extension ".txt“.
OFDialog.Filter = "Text Files|*.txt“-use shift+”\”
• You can add a little bit extra to the description part of the filter, if
you like. This will serve as a reminder of just what the extension is.
OFDialog.Filter = "Text Files(*.txt)|*.txt“;
To display files of more than one type, add a Pipe character between
each filter.
OFDialog.Filter = "Text Files(*.txt)|*.txt|Word
Files(*.doc)|*.doc“;
27
• You'll notice from the previous slides that if you select a file and click
the Open button, nothing happens.
– That's because the Open dialogue boxes doesn't actually open files! It
only displays a list of files that CAN be opened.
• The Open Dialogue box has a property that returns the file name
that was selected - it's called FileName.
string strFileName;
strFileName = OFDialog.FileName;
• To see what is actually returned by the property add the following
line and run your code
MessagBox.Show(strFileName);
• The file name selected as well as the location (the path) of the file is
displayed.
28
In your code, you will only want to do something with a file if the
Cancel button is NOT clicked. This can be done by adding the
following code.
DialogResult DidWork = OFDialog.ShowDialog();
if(DidWork == System.Windows.Forms.DialogResult.Cancel)
{
MessageBox.Show("Cancel Button Clicked");}
else
{
strFileName = OFDialog.FileName;
MessageBox.Show(strFileName);
29 }
Write a code to display picture in a picture box based on the opened
file.
DialogResult valuereturn =OFDialog.ShowDialog();
if (valuereturn ==DialogResult.Cancel)
MessageBox.Show("Cancel clicked");
else
pictureBox1.Image = Image.FromFile(OFDialog.FileName);
30
• The save dialogue box works in the same way as the Open dialogue
box. However, you can't use the same control.
– If you examine the Toolbox, you'll see a control called SaveFileDialog:
• Change the Name property of your control to something more
manageable. Change it to saveFD.
• Access the code for your File > Save menu item. Then add the
following code:
saveFD.ShowDialog();
• Run your program, then click your File > Save menu item.You
should see the Save As dialogue box appear.
31
• Just like the Open control, you can use the properties of the Save control on
your dialogue boxes.
• Try changing these properties, just like you did with the Open File Dialog:
Initial Directory, Title, Filter, FileName, …
• There's another useful property you can use with the Save control - the
Overwrite prompt.
• When you set this property, a message box pops up warning you that the file
will be overwritten, and do you want to continue. To use this property, the
code is this: saveFD.OverwritePrompt = true;
• However, just like the Open box, when you click the Save button no file is
actually being saved.You have to write your own code for this. E.g.:
DialogResult dr=saveFD.ShowDialog();
if (dr == DialogResult.OK)
richTextBox1.SaveFile(saveFD.FileName); else
32
return;
First, place two textboxes on your form. In the properties box,
locate the MultiLine property and set to true.
Type some default text for the Text Property of textbox1.
The Copy Menu
If you type Textbox1 in your code window, then a full stop, you get
a list of properties and methods available to the textbox. Scroll up to
the top and locate the Copy method
When you invoke the Copy method of the textbox, any selected text
is place in this temporary storage area for you.You don't have to
write any other code.
So access the code for your Copy menu item, and add this line to it:
Textbox1.Copy();
33
The Paste Menu
Again, there's only one line of code to write. It's this:
TextBox2.Paste();
Notice that we're saying paste to textbox2. Because the copy
menu places the text from textbox one onto the clipboard, you
only need this one line of code.You're saying "Whatever is on
the Clipboard, paste it into Textbox2".
Run your program. Select all the text in textbox one (it might
already be selected), then click Edit > Copy from your menu.
Click inside the second textbox. Then click Edit > Paste from
your menu. The text should appear in textbox two.
34
The Cut Menu
Access the code for you Cut menu item. Add the following code to it:
TextBox1.Cut();
Run your program, and select the text in textbox one.
From your menu, click Edit > Cut. The text should disappear (it's on
the clipboard, though).
Click inside textbox two, and click Edit > Paste. The text should be
pasted over.
The Undo Menu
For the Undo menu, add this line of code: TextBox1.Undo();
Run your program. Then select the text in textbox one. Click Edit >
Cut and the text disappears. Now click Edit > Undo. The text
reappears.
The Edit menu we implemented is only a simple one. But it does
35 demonstrate what you can do with C#.NET and menus.
Since you have two text boxes on your form,
you need a way to determine which text box you are dealing with
(Done earlier)or
a generic way of handling an undo operation for both text boxes.
You do the latter option by first determining whether the active control
you are dealing with is a TextBox control.
TextBox txt=null;
if (this.ActiveControl is TextBox)
{txt=(TextBox)Convert.ChangeType (this.ActiveControl, typeof(TextBox));}
txt.Undo();
The ActiveControl property of the Form class returns a reference to the
active control on the form, the control that has focus.
36
To Cut TextBox txt=null;
if (this.ActiveControl is TextBox)
{txt=(TextBox)Convert.ChangeType
(this.ActiveControl, typeof(TextBox));}
txt.Cut();
To Copy TextBox txt=null;
if (this.ActiveControl is TextBox)
{txt=(TextBox)Convert.ChangeType
(this.ActiveControl, typeof(TextBox));}
txt.Copy();
To Paste
TextBox txt=null;
if (this.ActiveControl is TextBox)
{txt=(TextBox)Convert.ChangeType
(this.ActiveControl, typeof(TextBox));}
37 txt.Paste();
We have seen how to add tool bars to an application. Now
lets see how to make it workable.[cut, copy and past buttons]
This can be done by calling the corresponding menu items
Cut Button
mnCut_Click(sender, e);
Copy Button
mnCopy_Click(sender, e);
PasteButton
mnPaste_Click(sender, e);
38
Controls on a form can be hidden or shown as the need arises.
To hide a control, simply set it's Visible property to False.
If you want to get it back, show a control by setting the
Visible property to True.
The items on our view menu are: Toolbars, View Textboxes,
View Labels, View Images
A control can be toggled on and off:
One click of a menu item could hide the control, and a second
click could show it again.
39
You can use this Checked property as a toggle:
If the menu item is ticked, display the textbox;
if it's not ticked, hide the textbox.
textBoxToolStripMenuItem.Checked =
!textBoxToolStripMenuItem.Checked;
if (textBoxToolStripMenuItem.Checked)
{
textBox1.Visible = true;
textBox2.Visible = true;}
else
{textBox1.Visible = false;
textBox2.Visible = false; }
40
Context menus are menus that pop up when a user clicks the right mouse button on
a control or window.
They provide the users with quick access to the most commonly used
commands for the control that they are working with.
Visual Studio 2010 provides a ContextMenuStrip control that you can
place on your form and customize, just as you did the MenuStrip control.
However, the main difference between the MenuStrip control and the
ContextMenuStrip control is that you can create only one top - level
menu with the ContextMenuStrip control.You can still create submenu
items with the ContextMenuStrip if you need to.
Most controls in the toolbox have a ContextMenuStrip property that can
be set to the context menu that you define. When you right - click that
control, the context menu that you defined is displayed instead of the
default context menu.
Some controls, such as the ComboBox and ListBox controls, do not have
41
a default context menu.
Return to the Forms Designer in your Windows Forms Menus
project and then click the toolbox to locate the ContextMenuStrip
control. Drag and drop it onto your form. It is added at the bottom
of the development environment just as the MenuStrip control
was.
To add context menu items
select the context menu - you will see context menu control at the
top.
Write the menu items on “Type Here” or
Use Items property of context menu.
The context menu should look like
42
Click the first text box on your form. In the Properties window,
select ContextMenuStrip1 in the drop-down list for the
ContextMenuStrip property. Repeat the same action for all text box
you have to assign a context menu in the ContextMenuStrip
property.
Test your context menu for look and feel. At this point, you haven’t
added any code to it, but you can ensure that it looks visually correct.
Run the application; then right-click in one of the text boxs, and you
will see the context menu that you have just added.
43
Stop your program and switch to the Code Editor for your form
so that you can add the code for the context menus.
Then add the code for each menu item as follows
For Undo context menu
mnUndo_Click(Sender, e)
Cut Button
mnCut_Click(sender, e);
Copy Button
mnCopy_Click(sender, e);
PasteButton
mnPaste_Click(sender, e);
44