Tải bản đầy đủ - 0 (trang)
Hour 9. Adding Menus and Toolbars to Forms

Hour 9. Adding Menus and Toolbars to Forms

Tải bản đầy đủ - 0trang

Hour9.AddingMenusandToolbarstoForms

TheuseofaGraphicalUserInterface(GUI)forinteractingwith

and navigating programs is one of the greatest features of

Windows. In spite of this, a fair number of Windows users still

relyprimarilyonthekeyboard,preferringtouseamouseonly

when absolutely necessary. Data-entry people in particular

never take their hands off the keyboard. Many software

companiesreceivesupportcallsfromangrycustomersbecause

acommonlyusedfunctionisaccessibleonlybyusingamouse.

Menus are the easiest way for a user who relies on the

keyboardtonavigateyourprogram.VisualStudioandC#make

iteasierthanevertocreatemenusforyourapplications.Inthis

hour,you'lllearnhowtobuild,manipulate,andprogrammenus

on a form. In addition, I'll teach you how to use the Toolbar

controltocreateattractiveandfunctionaltoolbars.Finally,you'll

learnhowto"finishoff"aformwithastatusbar.

Thehighlightsofthishourincludethefollowing:

Adding,moving,anddeletingmenuitems

Creatingcheckedmenuitems

Programmingmenus

Implementingcontextmenus

Assigningshortcutkeys

Creatingtoolbaritems

Definingtogglebuttonsandseparators

Creatingastatusbar









Top











BuildingMenus

WhenIsaidthatC#makesbuildingmenuseasierthanever,I

wasn'tkidding.Buildingmenusisnowanimmediatelygratifying

process.Ican'tstressenoughhowimportantitistohavegood

menus,andnowthatit'ssoeasytodo,thereisnoexcusefor

notputtingmenusinanapplication.



When running an application for the first time, users

often scan the menus before opening a manual. (Most

users never open the manual!) When you provide

comprehensive menus, you make your program easier

tolearnanduse.



AddingMenuItems

Addingmenus to a form is accomplished by way of a control:

the Main Menu control. The Main Menu control is a bit odd in

thatit'stheonlycontrolIknowofthatsitsatthebottomofthe

form in the space reserved for controls without an interface

(likeaTimercontrol),yetactuallyhasavisibleinterfaceonthe

form. Start by creating a new Windows Application project

namedMenusandMore.

1. Change the name of the default form to

fclsMenusAndMore, set its Text to Menus and More,

and change the Main entry point of the project to

referencefclsMenusAndMoreinsteadofForm1.

Next, add a new Main Menu control to your form by double-



clickingtheMainMenuiteminthetoolbox.Asyoucansee,the

controlisaddedtothepaneatthebottomoftheformdesigner.

Takealookatthetopoftheform—you'llseethetextTypeHere

(seeFigure9.1).

Figure9.1.Amenuhasnoitemswhenfirstaddedtoa

form.



Click this text and type &File. As you begin typing, C#

displaystwonewboxesthatsayTypeHere(seeFigure9.2).

Figure9.2.Creatingamenuitemautomaticallyprepares

thecontrolformoreitems.



Notice the Properties window (if it's not visible, press F4 to

show it). The text you just entered created a new menu item.

Each menu item is an object; therefore, the item has

properties. (You may have to press Tab to commit your entry

and then click the text you typed once more to see its

properties.)MenuItem1 isn't very descriptive, so change the

nameoftheitemtomnuFileMenu.



YoumayhavebeenwonderingwhyIhadyouenterthe

ampersand(&)infrontofthewordFile.Takealook

at your menu now, and you'll see that C# doesn't

display the ampersand; instead, it displays the text

with the F underlined, as in File. The ampersand,

whenusedintheTextpropertyofamenuitem,tellsC#

to underline the character immediately following it.

For top-level menu items, such as the File item you

justcreated,thisunderlinedcharacterisknownasan

accelerator key. Pressing Alt+ an accelerator key



opens the menu as if the user had clicked it. You

should avoid assigning the same accelerator key to

more than one top-level menu item on a given menu.

Whenthemenuitemappearsonadrop-downmenu,in

contrast to being a top-level item, the underlined

character is called a hotkey. When a menu is visible

(open), the user can press a hotkey to trigger the

correspondingmenuitemthesameasifitwasclicked.

Again, don't use the same hotkey for more than one

itemonthesamemenu.

Click the Type Here text that appears to the immediate right

of the File item and enter the text &Help. C# gives you two

moreTypeHereitems,thesameaswhenyouenteredtheFile

item. Adding new menu items is a matter of clicking a Type

Hereboxandenteringthetextforanitem.

Press Tab to commit your entry and then click the text you

typed once more to select it. Change the name of your new

menuiteminthePropertieswindowtomnuHelpMenu.



If you click a Type Here box below an existing menu

item, you'll add a new item to the same menu as the

item above the box. If you click the Type Here box to

therightofamenuitem,you'llcreateasubmenuusing

themenutotheleftoftheboxastheentrypointforthe

submenu. As you've already seen, clicking the Type

Hereboxalongthetopofthemenubarcreatesatoplevelmenu.



Click once more on the File item to display a Type Here box



belowtheitem.Clickthisboxandenterthetext&Quit.

Press Tab to commit your entry and then click the new item

once more to select it. Change the name of the new item to

mnuQuit.Nowisagoodtimetosaveyourwork,soclickSave

Allonthetoolbar.



MovingandDeletingMenuItems

Deleting and moving menu items are even easier processes

thanaddingnewitems.Todeleteamenuitem,right-clickitand

chooseDeletefromthecontextmenuthatappears.Tomovean

item,dragitfromitscurrentlocationanddropitinthelocation

inwhichyouwantitplaced.



CreatingCheckedMenuItems

A menu item that isn't used to open a submenu can display a

check mark next to its text. Check marks are used to create

menuitemsthathavestate—theitemiseitherselectedoritis

notselected.You'renowgoingtocreateacheckedmenuitem.

Click the Type Here box below the Quit menu item and enter

Ask before closing and then change the name of this new

item (remember to press Tab to commit your entry and then

click the item again to select it) to mnuAskBeforeClosing.

Next, change the Checked property of the new item to true.

Noticethatthemenuitemnowhasacheckmarknexttoit(see

Figure9.3).

Figure9.3.Menuitemscanbeusedtoindicatestate.



PressF5toruntheproject.Themenuwillappearonyourform,

justasyoudesignedit(seeFigure9.4).ClicktheFilemenuto

open it and then click Quit; nothing happens. In the next

section,I'llshowyouhowtoaddcodetomenuitemstomake

themactuallydosomething.Stoptheprojectbeforecontinuing.

Figure9.4.Whatyousee(atdesigntime)iswhatyouget

(atruntime).









Top











ProgrammingMenus

AsI'vesaidbefore,everymenuitemisauniqueobject—thisis

why you were able to change the name for each item you

created.Althoughindividualmenuitemsaren'tcontrols,perse,

addingcodebehindthemisverysimilartoaddingcodebehind

a control. You're now going to add code to the Quit and Ask

BeforeClosingmenuitems.

1. ClicktheFilemenunowtoopenit.

Double-click the Quit menu item. Just as when you doubleclick a control, C# displays the code editor with the default

eventforthemenuitemyou'veclicked.Formenuitems,thisis

theClickevent.

Enterthefollowingcode:



this.Close();

As you know by now, this code closes the current form, which

has the effect of stopping the project because this is the only

formandit'sdesignatedastheMainentrypointobject.

Switchbacktotheformdesigner(clicktheForm1.cs[Design]

tab).

You'renowgoingtocreatethecodefortheAskBeforeClosing

button.ThiscodewillinverttheCheckedpropertyofthemenu

item; if Checked = True, it will be set to false and vice

versa.

1. Double-clicktheAskBeforeClosingitemtoaccessits

Clickeventandenterthefollowingcode:



mnuAskBeforeClosing.Checked=(!mnuAskBeforeClosing.

Thelogicalnegationoperator(!)isusedtoperforma

negation of a Boolean value. Don't worry, I discuss

this in detail in Hour 13, "Performing Arithmetic,

String Manipulation, and Date/Time Adjustments."

For now, realize that if the current value of the

Checked property is true, (!Checked) returns false.

If Checked is currently false, (!Checked) returns

true. Therefore, the checked value will toggle

between true and false each time the menu item is

clicked.

Press F5 to run the project. Open the File menu by pressing

Alt+F(remember,theFistheacceleratorkey).

Next, click the Ask Before Closing button—it becomes

unchecked. Click the menu item once more and it becomes

checkedagain.

Clickitathirdtimetoremovethecheckmark,andthenclick

Quittoclosetheform.

Did you notice that you weren't asked whether you really

wanted to quit? This is because the quit code hasn't been

writtentoconsiderthecheckedstateoftheAskBeforeClosing

button.

1. Return to the Click event of the Quit button and

changeitscodetolooklikethis:



if(mnuAskBeforeClosing.Checked)

{

if(MessageBox.Show("Doyoureallywishtoexit?"

Verification",MessageBoxButtons.YesNo)==Dial

return;

}



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hour 9. Adding Menus and Toolbars to Forms

Tải bản đầy đủ ngay(0 tr)

×