Using Visual App Development to Create a Simple App that Displays Text and an Image

Một phần của tài liệu Visual C 2012 How to Program _ www.bit.ly/taiho123 (Trang 88 - 98)

2. When the app executes, another compiler (known as the just-in-time compiler

2.6 Using Visual App Development to Create a Simple App that Displays Text and an Image

Next, we create an app that displays the text"Welcome to Visual C#!"and an image of the Deitel & Associates bug mascot. The app consists of aFormthat uses aLabeland aPicture-

Box. Figure 2.20 shows the final app executing. The app and the bug image are available with this chapter’s examples. See the Before You Begin section following the Preface for download instructions. We assume the examples are located atC:\exampleson your computer.

You won’t write a single line of code. Instead, you’ll use visual app development tech- niques. Visual Studio processes your actions (such as mouse clicking, dragging and drop- ping) to generate app code. Chapter 3 begins our discussion of writing app code.

Throughout the book, you produce increasingly substantial and powerful apps that usually Fig. 2.19 | Using context-sensitive help.

Fig. 2.20 | Simple app executing.

PictureBox control Labelcontrol

include a combination of code written by you and code generated by Visual Studio. The gen- erated code can be difficult for novices to understand—but you’ll rarely need to look at it.

Visual app development is useful for building GUI-intensive apps that require a sig- nificant amount of user interaction. To create, save, run and terminate this first app, per- form the following steps:

1. Closing the open project.If the project you were working with earlier in this chap- ter is still open, close it by selectingFILE > Close Solution.

2. Creating the new project.To create a new WindowsForms app, selectFILE > New Project…to display theNew Projectdialog (Fig. 2.21). SelectWindows Forms Ap- plication. Name the projectASimpleApp, specify theLocationwhere you want to save it (we used the default location) and clickOK. As you saw earlier in this chap- ter, when you first create a new WindowsForms app, the IDE opens inDesign view (that is, the app is being designed and is not executing).

3. Setting the text in theForm’s title bar.The text in theForm’s title bar is deter- mined by theForm’sTextproperty(Fig. 2.22). If thePropertieswindow is not open, selectVIEW > Properties Window. Click anywhere in theFormto display the

Form’s properties in thePropertieswindow. In the textbox to the right of theText property, type"A Simple App", as in Fig. 2.22. Press theEnterkey—theForm’s title bar is updated immediately (Fig. 2.23).

4. Resizing theForm.Click and drag one of theForm’s enabledsizing handles(the small white squares that appear around theForm, as shown in Fig. 2.23). Using the mouse, select the bottom-right sizing handle and drag it down and to the right to make theFormlarger (Fig. 2.24).

Fig. 2.21 | New Projectdialog.

Type the project name here

Select theWindows Forms Applicationtemplate

2.6 Create a Simple App that Displays Text and an Image 49

5. Changing the Form’s background color. The BackColor property specifies a

Form’s or control’s background color. ClickingBackColorin thePropertieswin- Fig. 2.22 | Setting theForm’sTextproperty in thePropertieswindow.

Fig. 2.23 | Formwith enabled sizing handles.

Fig. 2.24 | ResizedForm.

Selected

property Property value

Name and type of object

Property description

Enabled sizing handles Title bar

dow causes a down-arrow button to appear next to the value of the property (Fig. 2.25). When clicked, the down-arrow button displays other options, which vary depending on the property. In this case, the arrow displays tabs forCustom,

WebandSystem(the default). Click theCustomtabto display thepalette(a grid of colors). Select the box that represents light blue. Once you select the color, the palette closes and theForm’s background color changes to light blue (Fig. 2.26).

6. Adding a Labelcontrol to the Form. If the Toolboxis notalready open, select

VIEW > Toolboxto display the set of controls you’ll use for creating your apps. For the type of app we’re creating in this chapter, the typical controls we use are lo- cated in either theAll Windows Formsgroup of theToolboxor theCommon Con- trolsgroup. If either group name is collapsed, expand it by clicking the arrow to the left of the group name (theAll Windows FormsandCommon Controlsgroups are shown in Fig. 2.17). Next, double click theLabel control in the Toolbox. Fig. 2.25 | Changing theForm’sBackColorproperty.

Fig. 2.26 | Formwith newBackColorproperty applied.

Down-arrow button Current color

Custompalette

Light blue

New light blue background color

2.6 Create a Simple App that Displays Text and an Image 51

This action causes a Label to appear in the upper-left corner of the Form (Fig. 2.27). [Note:If theFormis behind theToolbox, you may need to hide the

Toolboxto see theLabel.] Although double clicking anyToolboxcontrol places the control on theForm, you also can “drag” controls from theToolboxto the

Form—you may prefer dragging the control because you can position it wherever you want. TheLabeldisplays the textlabel1by default. When you add aLabel to theForm, the IDE sets theLabel’sBackColorproperty to theForm’sBackCol-

or. You can change theLabel’s background color by changing itsBackColor property.

7. Customizing theLabel’s appearance.Select theLabelby clicking it. Its properties now appear in thePropertieswindow. TheLabel’sTextproperty determines the text (if any) that theLabeldisplays. TheFormandLabeleach have their ownText property—Forms and controls can have thesameproperty names (such asBackCol-

or,Text, etc.) without conflict. Set theLabel’sTextproperty toWelcome to Vi- sual C#!. TheLabelresizes to fit all the typed text on one line. By default, the

AutoSizepropertyof theLabelis set toTrue, which allows theLabelto update its size to fit all of the text if necessary. Set theAutoSizeproperty toFalseso that you can resize theLabelon your own. Resize theLabel(using the sizing handles) so that the text fits. Move theLabelto the top center of theFormby dragging it or by using the keyboard’s left and right arrow keys to adjust its position (Fig. 2.28).

Alternatively, when theLabelis selected, you can center theLabelcontrol hori- zontally by selectingFORMAT > Center In Form > Horizontally.

8. Setting theLabel’s font size.To change the font type and appearance of theLa-

bel’s text, select the value of theFontproperty, which causes anellipsis button to appear next to the value (Fig. 2.29). When the ellipsis button is clicked, a di- alog that provides additional values—in this case, theFontdialog(Fig. 2.30)—

is displayed. You can select the font name (the font options may be different, de- pending on your system), font style (Regular,Italic,Bold, etc.) and font size (16,

18, 20, etc.) in this dialog. The Sample text shows the selected font settings.

Fig. 2.27 | Adding aLabelto theForm.

Labelcontrol

Under Font, selectSegoe UI, Microsoft’s recommended font for user interfaces.

UnderSize, select24points and clickOK. If theLabel’s text does not fit on a sin- gle line, itwrapsto the next line. Resize theLabelso that the words"Welcome to"

appear on theLabel’s first line and the words"Visual C#!"appear on the second line. Re-center theLabelhorizontally.

Fig. 2.28 | GUI after theFormandLabelhave been customized.

Fig. 2.29 | Propertieswindow displaying theLabel’sFontproperty.

Fig. 2.30 | Fontdialog for selecting fonts, styles and sizes.

Labelcentered with updatedText property Sizing

handles

Ellipsis button

Selected font

Font sample

2.6 Create a Simple App that Displays Text and an Image 53

9. Aligning theLabel’s text.Select the Label’sTextAlignproperty, which deter- mines how the text is aligned within theLabel. A three-by-three grid of buttons representing alignment choices is displayed (Fig. 2.31). The position of each but- ton corresponds to where the text appears in theLabel. For this app, set the

TextAlignproperty toMiddleCenterin the three-by-three grid—this selection centers the text horizontally and vertically within theLabel. The other Text-

Alignvalues, such asTopLeft,TopRight, andBottomCenter, can be used to po- sition the text anywhere within aLabel. Certain alignment values may require that you resize theLabelto fit the text better.

10. Adding aPictureBoxto theForm.ThePictureBoxcontrol displays images. The process involved in this step is similar to that ofStep 6, in which we added aLabel to theForm. Locate thePictureBoxin theToolbox(Fig. 2.17) and double click it to add it to theForm. When thePictureBoxappears, move it underneath the

Label, either by dragging it or by using the arrow keys (Fig. 2.32).

11. Inserting an image.Click thePictureBoxto display its properties in theProper-

tieswindow (Fig. 2.33). Locate and select theImageproperty, which displays a Fig. 2.31 | Centering theLabel’s text.

Fig. 2.32 | Inserting and aligning aPictureBox.

Text alignment options

Middle-center alignment option

Updated Label

PictureBox

preview of the selected image or(none)if no image is selected. Click the ellipsis button (or theChoose Image…link above the property description) to display the

Select Resourcedialog(Fig. 2.34), which is used to import files, such as images, for use in an app. Click theImport…button to browse for an image to insert, se- lect the image file and clickOK. We usedbug.pngfrom this chapter’s examples folder. The image is previewed in theSelect Resourcedialog (Fig. 2.35). Click

OKto use the image. Supported image formats include PNG (Portable Network Graphics), GIF (Graphic Interchange Format), JPEG (Joint Photographic Ex- perts Group) and BMP (Windows bitmap). To scale the image to thePicture- Box’s size, change theSizeModepropertytoStretchImage (Fig. 2.36). Resize the

PictureBox, making it larger (Fig. 2.37).

12. Saving the project.SelectFILE > Save Allto save the entire solution. The solution file (which has the filename extension.sln) contains the name and location of its project, and the project file (which has the filename extension.csproj) con- tains the names and locations of all the files in the project. If you want to reopen your project at a later time, simply open its.slnfile.

Fig. 2.33 | Imageproperty of thePictureBox.

Fig. 2.34 | Select Resourcedialog to select an image for thePictureBox.

Imageproperty value (no image selected)

2.6 Create a Simple App that Displays Text and an Image 55

Fig. 2.35 | Select Resourcedialog displaying a preview of selected image.

Fig. 2.36 | Scaling an image to the size of thePictureBox.

Fig. 2.37 | PictureBoxdisplaying an image.

Image file name

SizeMode property

SizeMode property set to StretchImage

Newly inserted image

13. Running the project.Recall that up to this point we have been working in the IDE design mode (that is, the app being created is not executing). Inrun mode, the app is executing, and you can interact with only a few IDE features—features that are not available are disabled (grayed out). The textForm1.cs [Design]in the project tab (Fig. 2.38) means that we’re designing theFormvisuallyrather than programmatically. If we had been writing code, the tab would have contained only the textForm1.cs. If there is an asterisk (*) at the end of the text in the tab, the file has been changed and should be saved. SelectDEBUG > Start Debuggingto ex- ecute the app (or you can press theF5key). Figure 2.39 shows the IDE in run mode (indicated by the title-bar textASimpleApp (Running) – Microsoft Visual Stu- dio Express 2012 for Windows Desktop). Many toolbar icons and menus are dis- abled, since they cannot be used while the app is running. The running app appears in a separate window outside the IDE as shown in the lower-right portion of Fig. 2.39.

14. Terminating execution.Click the running app’s close box (the in the top- right corner of the running app’s window). This action stops the app’s execution and returns the IDE to design mode. You can also selectDEBUG > Stop Debug- gingto terminate the app.

Fig. 2.38 | Debugging a solution.

DEBUGmenu

Một phần của tài liệu Visual C 2012 How to Program _ www.bit.ly/taiho123 (Trang 88 - 98)

Tải bản đầy đủ (PDF)

(1.020 trang)