Sie sind auf Seite 1von 49

Adding Menus to Windows Forms in C#

In this section, we'll show how to add menus to your forms. You'll add File, Edit, and View menus, with items on each menu, and even sub menus. Here's what you will create:

So start a new ro!ect by clic"in# File > New Project from the menu at the to of Visual $%. $reate a new Windows Application ro!ect. $all it anythin# you li"e. &hen your new form a ears, you can add a menu bar 'uite easily. Have a loo" at the (oolbo) on the left of Visual $%. *s well as the $ommon $ontrol tools, there is a section for Menus and Toolbars. $lic" the lus symbol ne)t to this to see the followin#:

(he one you want is MenuStrip, which is hi#hli#hted in the ima#e above. ,ouble clic" -enuStri and you'll see a menu bar a ear at the to of your form:

.ut notice what has a eared at the bottom of your Visual $% window:

(his is the -enuStri ob!ect itself. (he default 0ame for the -enuStri is menuStrip1. If your -enuStri is not selected, you can clic" on this icon at the bottom. &hen you do, you'll see all the 1ro erties for the -enuStri a ear in the 1ro erties &indow on the ri#ht hand side of Visual $%. *ddin# items to your menus is 'uite sim le. $lic" inside of the area at the to , where it says 2(y e Here2. 0ow ty e the word File.

Hit the Enter "ey on your "eyboard and your menu will loo" li"e this:

&hat you have done is to create the main menu item. (o add items to your File menu, clic" inside of the second 2(y e Here2 area ictured above. 0ow ty e the word New. Hit the Enter "ey on your "eyboard to add the menu item:

$lic" bac" on the word 0ew after you have hit the enter "ey. (his will select !ust this menu item, and no other. 3nce you create a menu item it has its own 1ro erties that you can chan#e. &ith the New item selected, have a loo" at the 1ro erties &indow on the ri#ht hand side of Visual $%:

(he 1ro erty we're interested in is the Name. It's a bit too lon# at the moment. So chan#e it tomnuNew, as in the ima#e below:

If you scroll down, you'll also see a Te t ro erty. It will say New, at the moment. It says 0ew because that's what you ty ed in the menu bar when you created this item. You could chan#e this here, if you wanted to. .ut leave the (e)t ro erty on 0ew. $lic" bac" on your menu at the to of your form, and then into the 2(y e here2 area !ust below 0ew. (y e the word 3 en:

Hit the Enter "ey on your "eyboard to create the 3 en menu item. $han#e its Name ro erty, !ust li"e you did for the 0ew item. $han#e the name to mnu!pen. $reate a Save menu item, underneath 3 en. $han#e its 0ame ro erty to mnuSa"e. Your File menu will then loo" li"e ours below:

&e'll now create !ust two more menu items, a dividin# line, and a 6uit item. (o create a dividin# line, clic" inside of the 2(y e Here2 area below Save. 0ow ty e a hy hen 7!ust to the ri#ht of the 8ero "ey on 9: "eyboard;. &hen you ress the Enter "ey, $% will turn the hy hen into a dividin# line. It should loo" li"e this:

*dd the #uit item below your dividin# line. $han#e the 0ame ro erty to mnu#uit. Your File menu is now com lete. (o see what it loo"s li"e, run your ro#ramme. You should have a blue toolbar runnin# across the to with a File menu. $lic" your File menu:

<

3f course, none of the menus wor", because you haven't written any code for them yet. &e'll do that soon. .ut !ust in case you don't fancy a blue menu bar runnin# across the to , this is easily chan#ed. $lic" the red = to halt your ro#ramme and return to Visual $%. 0ow clic" anywhere on the blue menu to select it. 3r clic" on menuStrip1 at the bottom of the screen. &ith the -enuStri selected, have a loo" at its 1ro erties in the 1ro erty &indow. >ocate one called$enderMode:

$lic" the down arrow to see more o tions. (he 1rofessional one doesn't do much. So select System.

0ow have a loo" at your -enuStri . It should have chan#ed to this:

&hen you run the ro#ramme, it loo"s li"e the one in the ima#e below:

In the ne)t art, you'll learn how to add sub menus.

Sub Menus in C# %N&T


You can add Sub -enus !ust as easily. * Sub menu is one that o ens out from a main menu item. Halt your ro#ramme and return to your form. $lic" on the New item to select it. You should see a 2(y e Here2 bo) a ear to the ri#ht of 0ew:

$lic" Inside of this bo) and ty e 'iew Project. Hit the enter "ey and ty e 'iew Files in the bo) below this. Your menu will then loo" li"e this:

&hen the form is run, the Sub -enu will loo" li"e this:

Sub menus are 'uite easy to addB In the me)t lesson, you'll learn how to add shortcuts to your menu items.

Menu S(ortcuts in C# %N&T


-enus usually have shortcuts. (hese are the underlined letters that you see when you clic" a menu. (hey sometimes have a shortcut "ey combination to the ri#ht of the menu item. For e)am le, here's the File menu from Visual $% with all the underlines and "ey combinations showin#:

(o see these, you need to hit the *>( "ey on your "eyboard. &hen you see the underlined letters, ress the "ey that corres onds to the underlined letter. 1ressin# the 2F2 "ey, for e)am le, will then cause the menu to dro down. 1ressin# any of the underlined letters on the File menu will im lement that menu item. 7In our edition of Visual $% E) ress, ressin# the letter 1 only switches bac" and forward between the first two items. (he other letters wor" 3:, thou#h.; You can also use the "ey combinations to the ri#ht of the menu item. Holdin# down $(D> E SHIF( E 0 at the same time will cause the 0ew 1ro!ect dialo#ue bo) to a ear. (o add shortcuts to your own menus, clic" your File item to select it. 0ow have a loo" at its 1ro erties in the 1ro erty &indow. Scroll down until you locate the te)t item:

+F

(o add an underline to any of the letters, you use the am ersand symbol 7G; before the letter you want to use as a shortcut. In the ima#e below, we've added an am ersand !ust before the 2F2 of File:

*nd here's what the menu loo"s li"e with the am ersand added:

*s you can see, there's now a line underneath the letter 2F2. In the ne)t ima#e, we've added more underlines to the rest of the File menu:

++

*dd the same underlines to your own File menu. Demember: clic" a menu item to select it, locate the te)t ro erty, and add an am ersand before the letter you want to use as a shortcut. &hen you run the ro#ramme, don't for#et to ress the *>( "ey on your "eyboard, otherwise you won't see the underlined letters. (he "ey combination shortcuts are !ust as easy to add. $lic" on your New menu item to select it. >ocate the S(ortcut)e*s 1ro erty in the 1ro erties &indow:

*t the moment, it's set to 0one. $lic" the down arrow to see the followin# o tions:

+/

(he -odifiers are the $(D>, Shift, and *>( "eys. You can select one or all of these, if you want. (o activate a shortcut, you would then have to hold down these "eys first. So if you want your users to hold down the $(D> and Shift "eys, lus a letter or symbol, then you would chec" the relevant -odifier bo)es above. (he letters and symbols can be found on the :ey dro down list. $lic" the down arrow to see the followin#:

In the ima#e above, we've #one for the $(D> modifier, and the letter 202. $lic"in# bac" on the menu, here's what it now loo"s li"e:

*s you can see, the shortcuts for the 0ew menu item are an 9nderline, and $trl E 0. Have a loo" at the ne)t ima#e, and add the same Shortcut :eys to your File menu:

+4

(he ones you are addin# are the final three: 3 en, Save and 6uit. &e'll #et to codin# the menu items shortly, but here's an e)ercise to com lete. 7,on't s"i this e)ercise because you'll need the menu itemsB;

& ercise *dd an Edit menu to your menu bar with the followin# items:

Include the underline shortcuts, and the "ey combination shortcuts. For the 0ame 1ro erty of each menu item, use the followin#: +ndo: mnu9ndo Cut: mnu$ut Cop*, mnu$o y Paste: mnu1aste & ercise *dd a View menu to your menu bar with the followin# items:

+5

*#ain, include the underline and "ey combination shortcuts. Set the 0ame 1ro erty of your menu items to the followin#: 'iew Te t -o es: mnuView(e)t.o)es 'iew .abels: mnuView>abels 'iew /mages, mnuViewIma#es 3:, it's now time to do some codin# for the menu items you have created.

C# Code 0or *our #uit Menu


3f course, a menu is no #ood if nothin# ha ens when you clic" an item. So we need to add code behind the menu items. &e'll start with the 6uit item, which should be on your File menu. (here's only one line of code for this. Deturn to your form, and clic" the menu stri . $lic" the File item to see its menu. ,ouble clic" on your#uit item and the codin# window should o en. Your cursor should be flashin# between the curly brac"ets of the 6uit code stub:

0otice that the 0ame you #ave your menu item is used in the code stub: mnu#uit. .ut when a user clic"s your 6uit menu, you want the ro#ramme to end. (o close down a &indows a lication, you can use this: Application%& it1 23 So add that line of code between the curly brac"ets of your 6uit code stub. Dun your ro#ramme and test it out. Hit the $(D> and SHIF( "eys, and then the letter 6 on your "eyboard. (he ro#ramme should close strai#ht away. It does this because of the "ey combination shortcuts you added. (o see your underline shortcuts in action, start your ro#ramme a#ain. 1ress the *>( "ey on your "eyboard and you should see all the underlines a ear for File, Edit and View. +<

1ress the letter 2F2 on your "eyboard 7the underlined letter;, and the menu should dro down. 0ow ress the letter 6 on your "eyboard. .ecause this is the underlined letter, the ro#ramme should e)it. You can add more code to menu items H anythin# you li"e, in fact. Somethin# you do see on 6uit menus is a messa#e bo): 4Are *ou sure *ou want to #uit54 (o add a messa#e bo) to your own code, try this: i0 1Message-o %S(ow14$eall* #uit546 4& it46 Message-o -uttons%!)Cancel2 77 8ialog$esult%!)2 9 Application%& it123 : (he first two lines should be one line in your code. It's only on two lines here because there's not enou#h room for it on this a#e. .ut in between the round brac"ets of an if statement, we have a messa#e bo): Message-o %S(ow14$eall* #uit546 4& it46 Message-o -uttons%!)Cancel2 (his will #et you a dialo#ue bo) with 3: and $ancel buttons. $% will wait until the user clic"s a button. 3ur code uses an if statement to test which button was clic"ed. (o see which one the user clic"ed, you add this on the end: 77 8ialog$esult%!) So the line reads 2IF the result of the dialo#ue bo) was that the 3: button was clic"ed, then E)it the * lication.2

In the ne)t art, you'll see how to code for your Edit menu.

+?

T(e &dit Menu


&e'll leave the rest of the File menu till last, as it's a bit more com licated. 3ur Edit menu is not too difficult, as there's only one line of code for each menu item. (o see $ut, $o y, 1aste and 9ndo in action, add two te)t bo)es to your form. Set the Multi.ine1ro erty of each te)t bo) to true. (his will allow you to have a te)t bo) with more than one line of te)t. For te)t bo) one, ty e anythin# you li"e for the (e)t ro erty. Your form should then loo" li"e this:

&hat's we'll do now is to enable the $ut, $o y and 1aste menu items, as well as the undo. &e'll first $ut the hi#hli#hted te)t from the te)t bo) and then 9ndo the o eration. So return to your Form. $lic" your blue menu bar at the to , and clic" on your Edit menu. ,ouble clic" the Cut item. $% will create a code stub for you. If you #ave your $ut menu item the 0ame of mnuCutthen your code stub will loo" li"e this:

+@

(he code to cut any hi#hli#hted te)t is 'uite sim le. *dd this between the curly brac"ets of your mnu$ut code: te t-o 1%Cut1 23 $ut7 ; is a method that's built in to $%. It wor"s on te)t bo)es, amon#st other thin#s, and does what it says H cutsB .efore you try it out, return to your form and double clic" your +ndo menu item. *dd the followin# line for the code: te t-o 1%+ndo1 23 0ow try it out. Dun your form and hi#hli#ht the te)t in the te)t bo). 9se your $ut menu to cut the te)t. (hen use your 9ndo menu to restore the te)t. You can also chec" to see if any te)t was selected. $han#e your code to this: i0 1te t-o 1%SelectedTe t ;7 442 9 te t-o 1%Cut123 : &e're usin# an if statement to chec" a ro erty of te)t bo)es called SelectedTe t. (his can tell you if any te)t is selected. &e're usin# the 2,oes 0ot E'ual2 o erators 7 BI ; followed by a air of double 'uotes. * air of double 'uotes with no s aces means that it's a blan" strin# of te)t. If no te)t was selected, then the if statement is true. In which case the $ut o eration can #o ahead. You can mani ulate selected te)t with the Selected(e)t 1ro erty. In the code below, we're handin# the selected te)t to a strin# variable and dis layin# it in a messa#e bo): string someTe t3 i0 1te t-o 1%SelectedTe t ;7 442 9 someTe t 7 te t-o 1%SelectedTe t3 Message-o %S(ow1someTe t23 :

+A

For the 9ndo menu, you mi#ht want to chec" if the o eration can actually be 9ndone. If you want to chec" for this, there is another ro erty of te)t bo)es called Can+ndo. You use it li"e this: i0 1te t-o 1%Can+ndo 77 true2 9 te t-o 1%+ndo123 : 3nly if the o eration can be 9ndone will the code for the if statement e)ecute. However, if you run your ro#ramme and cut some te)t, clic"in# 9ndo twice will first restore the te)t and then cut it a#ainB 7You're undoin# the restore.; (o remedy this, you can clear the undo o eration. $han#e your code to this. (he new line is in blac" bold te)t below: i0 1te t-o 1%Can+ndo 77 true2 9 te t-o 1%+ndo123 te t-o 1%Clear+ndo123 : So you !ust add the $lear9ndo7; method after the dot of te)t.o)+. (ry it a#ain and you'll find that clic"in# 9ndo twice won't cut the te)t a#ain.

In the ne)t art, you'll see how to $o y and 1aste in $%.

Cop* and Paste in C# %N&T


(o $o y somethin# to the $li board, you hi#hli#ht te)t and clic" a $o y item on an Edit menu. 3nce the data is co ied to the $li board, it can be 1asted elsewhere. &e'll im lement this with our menu system. ,ouble clic" the Cop* item on your &dit menu. You'll be ta"en to the code stub for your $o y menu item. *dd the followin# code between the curly brac"ets: te t-o 1%Cop*123

+C

9sin# the $o y method of te)t bo)es is enou#h to co y the data on to the &indows $li board. .ut you can first chec" to see if there is any hi#hli#hted te)t to co y. $han#e your code to this: i0 1te t-o 1%Selection.engt( > <2 9 te t-o 1%Cop*123 : &e're usin# an if statement a#ain. (his time, we are chec"in# the Selection.engt( ro erty of te)t bo)es. (he len#th returns how many characters are in the te)t that was selected. &e want to ma"e sure that it's #reater than 8ero. &e'll use the second te)t bo) to 1aste. So access the code stub for your 1aste menu item, usin# the same techni'ue as before. *dd the followin# between the curly brac"ets of your 1aste code: te t-o =%Paste123 0otice that we're now usin# te)t.o)/ and not te)t.o)+. *fter the dot, you only need to add the 1aste method. (ry your Edit menu out a#ain. Hi#hli#ht the te)t in the first te)t bo). $lic" &dit > Cop*. 0ow clic" into your second te)t bo) and clic" &dit > Paste. You can also chec" to see if there is any data on the $li board, and that it is te)t and not, say, an ima#e. *dd this rather lon# if statement to your code: i0 1Clipboard%>et8ata!bject12%>et8ataPresent18ataFormats%Te t2 77 true2 9 te t-o =%Paste123 Clipboard%Clear123 : Jettin# at the data on the $li board can be tric"y, but we're chec"in# to see what the ,ataFormat is. If it's te)t then the if statement is true, and the code #ets e)ecuted. 0otice the last line, thou#h: Clipboard%Clear123

/F

*s you'd e) ect, this $lears whatever is on the $li board. You don't need this line, however, so you can delete it if you refer. See what it does both with and without the line.

In the ne)t art, we'll code for the View menu.

T(e 'iew Menu


&e have three items on our 'iew menu. .ut we'll only im lement two of them. For the first one, View (e)t .o)es, we'll show you a handy ro#rammin# techni'ue with .oolean variables H how to to##le them on and off. So return to your form, and double clic" the menu item for 'iew Te t -o es. $% will #enerate the code stub for you:

&hat we'll do is to hide the te)t bo)es when the menu item is clic"ed, and unhide the te)t bo)es when you clic" a#ain. * chec" icon will then a ear or disa ear ne)t to the menu item. Here's an ima#e of what we'll be doin#:

(o lace a chec" mar" ne)t to a menu item, you use the C(ec?ed 1ro erty of the menu item. *dd this to your View (e)tbo)es code stub, in between the curly brac"ets: mnu'iewTe tbo es%C(ec?ed 7 true3 So you !ust ty e a dot after the 0ame of your menu item. (hen select the C(ec?ed ro erty from the IntelliSense list. $hec"ed is a .oolean value that you either set to true or false 7it's either #ot a chec" mar" ne)t to it or it hasn't;. Dun your ro#ramme and clic" your 'iew Te tbo es menu item. You should see a chec" a ear. It does so because the default value for the $hec"ed ro erty is false. It only becomes true when you clic" the menu item, thereby runnin# the code you added. /+

(he 'uestion is, how do you #et the $hec" mar" symbol to disa ear when it's clic"ed a#ainK 3bviously you need to set it to false, meanin# not chec"ed. .ut what's the codeK * handy ro#rammin# techni'ue is to to##le .oolean values off and on. You do it with the aid of the 03( o erator 7 B ;. *mend your code to this: mnu'iewTe tbo es%C(ec?ed 7 ;mnu'iewTe tbo es%C(ec?ed3 So instead of settin# the $hec"ed value to true, we have this: ;mnuView(e)tbo)es.$hec"edL (his says, 203( $hec"ed2. .ut doesn't mean 29nchec"ed2. &hat you are doin# is settin# the .oolean variable to what it is currently 03(. Demember: $hec"ed can either be true 3D false. So if $hec"ed is currently true, set it to false, and vice versa. (he result then #ets stored bac" in the 1ro erty on the left of the e'uals si#n. Dun your ro#ramme and try it out. $lic" the menu item to see the $hec" symbol. $lic" it a#ain and it will disa ear. (his to##lin# of .oolean variables is 'uite common in ro#rammin#, and can save you a lot of tric"y codin#B (o actually do somethin# with the te)t bo)es, thou#h, you can add an if statement to e)amine whether the variable is true. &hat we'll do is ma"e the te)t bo)es visible if there's a $hec", and not visible if there isn't a $hec". *dd this code !ust below the line you already have: i0 1mnu'iewTe tbo es%C(ec?ed2 9 te t-o 1%'isible 7 true3 te t-o =%'isible 7 true3 : else 9 te t-o 1%'isible 7 0alse3 te t-o =%'isible 7 0alse3 : (he 1ro erty we are chan#in# is the 'isible 1ro erty of te)t bo)es. *s its name su##ests, this hides or unHhides an ob!ect. *#ain, it's a .oolean value, thou#h. So we could have !ust done this: te t-o 1%'isible 7 ;te t-o 1%'isible3

//

(he use of the 03( o erator will then to##le the Visibility on or off. &e added an if statement because it's handy to actually e)amine what is in the variable, rather than !ust assumin#. 3ne line you may u88le over is this: i0 1mnu'iewTe tbo es%C(ec?ed2 (he art in round brac"ets could have been written li"e this, instead: if 7mnuView(e)tbo)es.$hec"ed 77 true; For if statements, $% is tryin# to wor" out if the code in round brac"ets is true. So you can leave off the 2II true2 art, because it's not needed. If you want to chec" for false values, you can use the 03( o erator a#ain. >i"e this: i0 1;mnu'iewTe tbo es%C(ec?ed2 (his is the same as sayin# this: if 7mnuView(e)tbo)es.$hec"ed 77 0alse; 9sin# the 03( o erator is considered more rofessional. (hey mean the same, thou#h, so use which one is better for you.

In the ne)t art you'll see how to add ima#es to your $% ro#rammes.

Adding /mages in C# %N&T


You have seen the 3 en File dialo#ue bo) countless times. It's the one that a ears whenever you clic" File > !pen on a &indows machine. You then navi#ate throu#h folders, searchin# for the file you want to o en. For our View Ima#es menu, we'll do somethin# sli#htly more com le) H we'll have our own 3 en File dialo#ue bo) that allows you to select ima#es from your com uter. &hen you select an ima#e, it will then a ear in a new control on your form. So we need a lace on our form where we can store ima#es. &e'll use a 1icture .o). Have a loo" at the (oolbo) on the left hand side of Visual $%. 9nder Common Controls, locatePicture-o :

/4

3nce you've select the 1icture.o) tool. $lic" on your form once to add a new 1icture.o) control. Your form should then loo" li"e this:

/5

(he 1icture.o) control is blan" when you first add one. (o add an ima#e to it at ,esi#n (ime, have a loo" at the 1ro erties &indow. >ocate the /mage ro erty:

$lic" the button with the three dots on it to see a dialo#ue bo) a ear: /<

$lic" the Im ort button at the bottom and you'll see a standard 3 en dialo#ue bo). Search your hard drive for a suitable ima#e. .ecause you have 21ro!ect resource file2 selected, $% will co y the ima#e to a folder in your ro!ect. 7(his is handy if you want to send your ro#ramme to anyone else.; In the ima#e below, we've #one for a icture of a lanet:

/?

$lic" 3: and you'll be ta"en bac" to your form:

0otice that the ima#e is too bi# for the 1icture.o). >ocate the Si@eMode ro erty in the 1ro erties &indow:

*s you can see, there are a few to choose form. Select AutoSi@e, and the 1icture.o) will automatically stretch to the si8e of your ima#e:

/@

If you run your ro#ramme, you'll see the ima#e a ear on the form. It won't have a border, thou#h. If you want a border, e) lore the -orderSt*le 1ro erty of your 1icture.o) control.

In the ne)t art, you'll see how to add an 3 en File dialo#ue bo) to a ro!ect, allowin# you to select any ima#e you want.

!pen File 8ialogue -o in C#


&e'll now #ive users the o tion to add their own ima#es to the icture bo), instead of the one we chose. (o do that, you need to dis lay an 3 en File dialo#ue bo) when the user clic"s your 'iew > 'iew /mages menu item. ,ialo#ue bo)es in $% can be added with the aid of an inbuilt ob!ect. Have a loo" in the (oolbo) on the left hand side of Visual $%. (here should be a cate#ory called ,ialo#s:

/A

*ll the dialo#ue bo)es you are familiar with in &indows are on the list above. (he one hi#hli#hted is the one we want H !penFile8ialog. ,ouble clic" this item, and you'll see a new item a ear at the bottom of Visual $%, ne)t to your menuStri + ob!ect:

0othin# will a ear on your form, however, because the ,ialo# controls are are hidden from view. (he one in the ima#e above has a default 0ame of openFile8ialog1. (his is a bit lon#, so have a loo" at the 1ro erties &indow on the ri#ht. $han#e the Name to openF8:

/C

(he control at the bottom of Visual $% should have chan#ed, as well:

&ith the control selected, have another loo" at the 1ro erties &indow. You'll see that there are 1ro erties for Filter, FileName, /nitial8irector* and Title. &e'll chan#e these with code. .ut one im ortant oint to bear in mind about the 3 en File ,ialo#ue bo) is this: (hey don't actually o en filesB &hat the 3 en File ,ialo#ue bo) does, and the same is true for the other ,ialo# controls, is to allow you to select a file for o enin#. You have to write se arate code to o en anythin#. (he only thin# you're really doin# here is to #et at a file name. &e want the dialo#ue bo) to a ear when the 'iew > 'iew /mages menu is clic"ed. So double clic" this item on your 'iew menu. * code stub will a ear:

(o see the 3 en ,ialo#ue bo), add this line to your code, in between the curly brac"ets: 4F

openF8%S(ow8ialog123 So you ty e the 0ame of your control, and then a dot. *fter the dot, select S(ow8ialog from the IntelliSense list. *s its name su##est, this shows you the dialo#ue bo). Dun your ro#ramme and try it out. You should see somethin# li"e the followin# a ear when you clic" your 'iew > 'iew /mages menu item:

.ecause we haven't yet set any 1ro erties, a default location is dis layed, which is the ,ocuments folder in &indows @. (he File name has the default o enFile,ialo#+. You can chan#e all these, thou#h. &e can set a (itle, first. (he default (itle is the word 3 en, in white on a blue bac"#round in =1, blac" on li#ht blue bac"#round in Vista and &indows @. *dd this line to your code, before the first line: openF8%Title 7 4/nsert an /mage43

4+

(his time, we're usin# the Title 1ro erty, and settin# it to the te)t 2Insert an Ima#e2. You can, of course, ty e anythin# you li"e here. &hen you run your ro#ramme and clic" the menu item, the new (itle will loo" li"e this in =1:

*nd this in later versions of &indows:

If you wanted somethin# more humorous, you could even chan#e it somethin# li"e this:

.etter to stic" with somethin# more descri tive, thou#hB *nother thin# you can chan#e is that >oo" in area. (he default location is the ,ebu# folder from your ro!ect. You can reset it with the Initial,irectory ro erty. *dd the followin# line to your code, before the other two lines: openF8%/nitial8irector* 7 4C,43 &e're settin# the default folder to be $. (his would assume that the user had a hard drive called $. If you want to set the Initial ,irectory to the 2-y ,ocuments2 folder of any com uter, try this after the e'uals si#n, instead of 2$:2: 7 S*stem%&n"ironment%>etFolderPat(1&n"ironment%SpecialFolder%Personal23 (his will #et the folder ath to the -y ,ocument folder 71ersonal folder;, which is called the ,ocuments folder in Vista and &indows @. You need to do it this way because different users will have different user names, and there's no way for you to tell beforehand. .ut run your ro#ramme and try it out. (he >oo" in bo) should have chan#ed 7=1;:

4/

3r this, in later versions of the &indows o eratin# system:

For the File name area, you can use the FileName 1ro erty. *dd this line to your code 7add it before the final line;: openF8%FileName 7 443 Here, we're settin# the File 0ame to a blan" strin#. Dun your ro#ramme and you'll find that the File name area on your dialo#ue bo) will be blan", and the cursor will be flashin# away. Select any file you li"e, and the file name will a ear in the bo). (he ne)t thin# to do is to set u some Files of ty e. (his is for the dro down list you see at the bottom, !ust under File name. Here's what we want to do 7=1;:

*nd this in later versions of &indows:

So we want the user to be able to select M1EJ ima#es, JIF ima#es, and .itma ima#es. &hen you set the files of ty e, you are restrictin# the ty e of files that the user can o en. (his is done with the Filter 1ro erty. *fter all, you don't want your users tryin# to insert te)t files into a icture bo)B (he filter ro erty ma"es use of the i e character 7 N ;. (he i e character can be found above the bac"slash on a 9: "eyboard. *dd this code, !ust before the last line: openF8%Filter 7 4AP&>BC%jpg43 0otice what comes after the e'uals si#n: 2M1EJBO.! #2L

44

Your filters need to #o between 'uote mar"s. .ut the M1EJ art, before the i e character, is what you want to dis lay in the dro down list. You can have anythin# you li"e here, 2M1EJ Ima#es2 instead of !ust 2M1EJ2, for e)am le. *fter the i e character, you need an asteris" symbol O followed by a dot. (he asteris" symbol means 2any file name2. *fter the dot, you ty e the file e)tension that you want to filter for. Dun you code and try it out. You should see this in the 2Files of ty e2 list 7on the ri#ht of the te)t bo) in Vista and &indows @;::

0ow chan#e your code to this: openF8%Filter 7 4AP&> /magesBC%jpg43 (he 2Files of ty e2 list will then loo" li"e this, de endin# on your 3 eratin# System:

9sin# !ust one filter means that no other file ty es will dis lay. (o add other file ty es you !ust need to use the i e character a#ain. >et's add JIF ima#es, as well. $han#e your code to this: openF8%Filter 7 4AP&> /magesBC%jpgB>/F /magesBC%gi043 *s you can see, the line is a bit messyB (he new art is in blue, thou#h. 0otice that you se arate one file ty e from another with a i e character. .ut you also need a i e to se arate the te)t for the dro down list from the actual file ty e. (o add .itma ima#es, the code would be this: openF8%Filter 7 4AP&> /magesBC%jpgB>/F /magesBC%gi0B-/TMAPSBC%bmp43 In the line above, the three file ty es have been dis layed usin# different colours, so that you can see them better. Here's a few more ima#e ty es, and their file e)tensions:

45

T/FF /mages: O.tif or O.tiff PN> /mages: O. n# P/CT /mages: O ct or O. ict (here are, of course, lots of others. In the ima#e below, we've added (IFF files to the list. 70ote that you can use u er or lower case for the e)tensions.;:

(o dis lay files of any ty e, use an asteris" symbol in lace of the file e)tension. For e)am le: openF8%Filter 7 4AP&> /magesBC%jpgBAll FilesBC%C43 However, we still haven't inserted a new ima#e. (o lace a selected ima#e into the icture bo), you have to #et the file name that the user selected. You can add a strin# variable to your code for this: string C(osenDFile 7 443 You then access the File0ame ro erty of o enF,. >i"e this: C(osenDFile 7 openF8%FileName3 (he file name will then be in the variable we've called C(osenDFile. (o lace a new ima#e into the icture bo) you have on the form, you need the Ima#e ro erty: picture-o 1%/mage (o lace your chosen file into the Ima#e ro erty, you need this: picture-o 1%/mage 7 /mage%FromFile1$hosenPFile23 So after the e'uals si#n, you can use the /mage ob!ect. (his has a method called FromFile7 ;. In between the round brac"ets of this method, you ty e the name of the ima#e file. For us, this ima#e file is stored in our $hosenPFile variable. *dd the new lines to your code and your codin# window should loo" somethin# li"e ours below 7we've cut down on a few filters;:

4<

Dun your ro#ramme and test it out. Select an ima#e to o en. You should find that your new ima#e re laces the old one in your icture bo). However, there is a roblem with the code. Instead of clic"in# 3 en, clic" Cancel. You should #et an error messa#e 7$% /F+/'s error messa#e is a lain version of the one below;:

.ecause the $ancel button was clic"ed, there is no ima#e name in the variable $hosenPFile. So the ro#ramme 2bu#s out2 on you. You need to handle this in your code. (o chec" if the cancel button was clic"ed, you can use this: i0 1openF8%S(ow8ialog12 7 7 8ialog$esult%Cancel2 9 Message-o %S(ow14!peration Cancelled423

4?

: So there is inbuilt ob!ect called 8ialog$esult. You chec" if this has a value of Cancel. *ddin# an else statement #ives us this code:

$han#e your code so that it loo"s li"e ours above. &hen you run your ro#ramme now, it shouldn't crash when you clic" the $ancel button. You can also have this for you IF Statement, instead of the one above: i0 1openF8%S(ow8ialog12 ;7 8ialog$esult%Cancel2 9 C(osenDFile 7 openF8%FileName3 picture-o 1%/mage 7 /mage%FromFile1C(osenDFile23 : &e've used the 03( symbol, here 7 B ;. So we're chec"in# if ,ialo#Desult does 03( e'ual $ancel.

In the ne)t art, you'll see how to use the 3 en File ,ialo#ue bo) to insert a te)t file into your te)t bo)es.

4@

!pen a Te t File wit( t(e !pen File 8ialogue -o


&e can reuse the 3 en File dialo#ue bo) that we have added. Instead of filterin# for ima#es, we'll filter for te)t files. &e'll also add a different "ind of te)t bo) H the Dich (e)t .o). (his will allow us to easily add the te)t from the file, strai#ht into the ro#ramme. So return to ,esi#ner View, so that you can see your form. 0ow e) and the (oolbo), and locate Dich(e)t.o), under $ommon $ontrols:

,ouble clic" to add a $ic(Te t-o to your form. You may have to ad!ust the hei#ht and width of your form, and re osition other controls. .ut your form should loo" li"e this, when you've added the Dich(e)t.o):

4A

(he Dich(e)t.o) is the one at the bottom H it loo"s e)actly the same as a normal te)t bo), but you can do more with it. 3ne -ethod it does have is called .oadFile7 ;. &e'll use this to load a te)t file. 0ow that we've added the Dich(e)t.o), we can add some code. So, access the code stub for youFile > !pen menu item. It should loo" li"e this:

&e can add the same lines as before. So add this to your code: string C(osenDFile 7 443 openF8%/nitial8irector* 7 4C,43 openF8%Title 7 4!pen a Te t File43 openF8%FileName 7 443 (he only thin# we've chan#ed here is the (itle ro erty. For the ne)t line, we can add the Filters: openF8%Filter 7 4Te t FilesBC%t tBWord 8ocumentsBC%doc43 (he Dich(e)t.o) can o en lain te)t files as well as &ord documents, so we've added both of these to the Filter ro erty. 7It can't handle &ord documents very well, thou#h.; (he ne)t thin# to do is to dis lay the 3 en File ,ialo#ue bo), so that a file can be selected. *dd the followin# to your code: i0 1openF8%S(ow8ialog12 ;7 8ialog$esult%Cancel2 9 C(osenDFile 7 openF8%FileName3 ric(Te t-o 1%.oadFile1C(osenDFile6 $ic(Te t-o StreamT*pe%PlainTe t23 : (his is more or less the same as before. .ut notice the line that adds the te)t file to Dich(e)t.o): rich(e)t.o)+.>oadFile7$hosenPFile, $ic(Te t-o StreamT*pe.1lain(e)t;L

4C

You'll see a better way to o en u a te)t file later in the course. For now, run your ro#ramme and test that it wor"s. You should be able to add lain te)t file to the Dich(e)t.o).

In the ne)t lesson, you'll see how to add a Save *s dialo#ue bo) to your $% ro#rammes.

Add a Sa"e As 8ialogue -o to *our C# Programmes


*nother useful -ethod you can use with the $ic(Te t-o is Sa"eFile7 ;. *s its name su##ests, this allows you to save the file that's currently in the te)t bo). &e'll use this with another ,ialo# ob!ect. (his time, we'll use the Sa"eFile8ialog control instead of the 3 enFile,ialo# control. Deturn to you form, and locate the SaveFile,ialo# control in the (oolbo):

,ouble clic" to add one to your ro!ect. It should a ear at the bottom of your screen:

$lic" on sa"eFile8ialog1 to select it. 0ow have a loo" at the 1ro erties on the ri#ht hand side of the screen. $han#e the Name ro erty to sa"eF8:

5F

0ow #o bac" to your File menu, on your -enu Stri . $lic" on File, then double clic" your Sa"e menu item. (his will o en u the code for this item:

(he code to add a Save o tion is ractically the same as for the 3 en menu item. Instead of sayin# o enF,, thou#h, it's saveF,. Here it is:

5+

You should be able to wor" out what's ha enin#, in the code above. (he line that does the savin# is this one: ric(Te t-o 1%Sa"eFile1Sa"edDFile6 $ic(Te t-o StreamT*pe%PlainTe t23 *#ain, thou#h, there is a better way to mani ulate files. You'll learn all about how to handle te)t files in a later section. For now, add the code above and Dun your ro#ramme. $lic" your File > !pen menu item to add a te)t file to your Dich (e)t .o). -a"es some chan#es to the te)t. (hen clic" your File > Sa"e menu item. You should find that the chan#es are ermanent. 3:, let's move on from menus. In the ne)t section, we'll ta"e a loo" at $hec".o)es and Dadio .uttons.

C# %N&T E C(ec?bo es and $adio -uttons


$hec"bo)es and Dadio .uttons are way to offer your users choices. $hec"bo)es allow a user to select multi le o tions, whereas Dadio .uttons allow only one. >et's see how to use them. Start a new ro!ect. &hen your new form a ears, ma"e it nice and bi#. .ecause $hec"bo)es and Dadio .uttons are small and fiddly to move around, its best to lace them on a Jrou bo). You can then move the Jrou bo), and the $hec"bo)es and Dadio .uttons will move with them. >ocate the Jrou bo) control in the (oolbo) on the left, under $ontainers. It loo"s li"e this:

5/

,raw one out on your form. >ocate the (e)t ro erty in the ro erties window on the ri#ht of $%. $han#e the (e)t ro erty to W(at T*pe o0 Mo"ies 8o Fou .i?e5. *dd a second Jrou bo) alon# side of the first one, and set the (e)t ro erty as And Four Fa"ourite /s5. Your form will then loo" li"e this:

&e'll lace some $hec"bo)es on the first Jrou bo), and some Dadio .uttons on the second one. >ocate the C(ec?bo control on the toolbo), under Common Controls. ,raw one out on your first Jrou bo). In the ro erties area on the ri#ht, notice that the default 0ame ro erty is c(ec?-o 1. >eave it on this, but locate the Te t ro erty and chan#e it to Comed*:

,raw four more chec"bo)es on the Jrou bo), and set the (e)t ro erties as follows: *ction, Science Fiction, Domance, *nimation. 7You can co y and aste the first one,

54

instead of drawin# them out.; -a"e the (e)t bold, and your Jrou bo) should loo" li"e this:

You add Dadio .uttons in the same. So add five Dadio .uttons to the second Jrou bo). >eave the 0ame ro erty on the defaults. .ut chan#e the (e)t to the same as for the $hec"bo)es. Your form should loo" li"e ours below when you are finished:

0ow add two buttons, one below each #rou bo). Set the (e)t for the first one as Selected -ovies. Set the (e)t for the second one as Favourite -ovie. Here's what your form should loo" li"e now:

55

Dun your form and test it out. &hat you should find is that you can select as many chec"bo)es as you li"e, but only one of the Dadio .uttons. Sto your ro#ramme and return to ,esi#n (ime. &hat we'll do now is to write code to #et at which selections a user made. First, the $hec"bo)es. ,ouble clic" your Selected Mo"ies button to o en u the code window. 3ur code will ma"e use of theC(ec?ed ro erty of $hec"bo)es. (his is either true or false. It will be true if the user laces a chec" in the bo), and false if there is no chec". &e can use if statements to test the values of each chec"bo). &e only need to test for a true value: i0 1c(ec?-o 1%C(ec?ed2 9 : &e can also build u a messa#e, if an o tion was selected: string mo"ies 7 443 i0 1c(ec?-o 1%C(ec?ed2 9 mo"ies 7 mo"ies G c(ec?-o 1%Te t3

5<

: Message-o %S(ow1mo"ies23 Inside of the if statement, we are buildin# u the strin# variable we've called movies. &e're lacin# the (e)t from the $hec"bo) into this variable. *dd a second if statement to your code: string mo"ies 7 443 i0 1c(ec?-o 1%C(ec?ed2 9 mo"ies 7 mo"ies G c(ec?-o 1%Te t3 : i0 1c(ec?-o =%C(ec?ed2 9 mo"ies 7 mo"ies G c(ec?-o =%Te t3 : Message-o %S(ow1mo"ies23 (he second if statement is the same as the first, e)ce t it refers to chec".o) / instead of chec".o)+. (est out your code so far. Dun your ro#ramme and chec" both bo)es. $lic" your button and the messa#e bo) should dis lay the followin#:

*s you can see, they are both on the same line, with no s acin#. Sto your ro#ramme and return to your code. (o #et the choices on se arate lines, there are a few ways you can do it. 3ne way is to use the return and new line characters, li"e this:

5?

movies I movies E chec".o)+.(e)t G 4HrHn4L (he 2Qr2 #ets you a Deturn character, and the 2Qn2 #ets you a 0ewline character. .ut you can also use the inbuilt 0ewline character. >i"e this: movies I movies E chec".o)+.(e)t G &n"ironment%New.ineL Newline is a ro erty of the &n"ironment class. *s its name su##ests, it adds a new line to your te)t. *dd one of the 0ewline o tions to both of your if statements, and then test it out. Your messa#e bo) will loo" li"e this, with both o tions chec"ed:

Deturn to your code, and add three more if statements. &hen you are finished, your codin# window should loo" li"e this one:

5@

&hen you run your ro#ramme and chec" all the bo)es, the messa#e bo) will loo" li"e this, after the button is clic"ed:

(o #et at which Dadio .utton was chosen, the code is the same as for $hec"bo)es H !ust test the $hec"ed stated. (he only difference is that you need else if, instead of < se arate if statements: string C(osenMo"ie 7 443

5A

i0 1radio-utton1%C(ec?ed2 9 C(osenMo"ie 7 radio-utton1%Te t3 : else i0 1radio-utton=%C(ec?ed2 9 C(osenMo"ie 7 radio-utton=%Te t3 :

& ercise Finish the code for your Dadio .uttons by addin# three more else R if arts. ,is lay a user's favourite movie ty e in a messa#e bo). &hen you've com leted this e)ercise, your messa#e bo) should loo" somethin# li"e ours below:

3:, let's move on from $hec"bo)es and Dadio buttons. In the ne)t section, we'll ta"e a loo" at how to ,ebu# your code.

5C

Das könnte Ihnen auch gefallen