microsoft visual basic 2008 step by step phần 8 pdf

57 622 0
microsoft visual basic 2008 step by step phần 8 pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 14 Managing Windows Forms and Controls at Run Time 371 To Do this Create a new form with program code and set its properties Create the form by using the Dim and New keywords and the Form class, and then set any necessary properties. For example: Dim form2 As New Form form2.Text = "My New Form" Position a startup form on the Windows desktop Set the StartPosition property to one of the available options, such as CenterScreen or CenterParent. Size and position a start- up form on the Windows desktop by using code Set the StartPosition to Manual, declare a Rectangle structure that defi nes the form’s size and position, and then use the DesktopBounds property to size and position the form on the desktop. For example: form2.StartPosition = FormStartPosition.Manual Dim Form2Rect As New Rectangle _ (200, 100, 300, 250) form2.DesktopBounds = Form2Rect Minimize, maximize, or restore a form at run time Set the MaximizeBox and MinimizeBox properties for the form to True in design mode to allow for maximize and minimize operations. In the pro- gram code, set the form’s WindowState property to FormWindowState. Minimized, FormWindowState.Maximized, or FormWindowState.Normal when you want to change the window state of the form. Add controls to a form at run time Create a control of the desired type, set its properties, and then add it to the form’s Controls collection. For example: Dim button1 as New Button button1.Text = "Click Me" button1.Location = New Point(20, 25) form2.Controls.Add(button1) Anchor an object a specifi c distance from specifi c edges of the form Set the Anchor property of the object, and specify the edges you want to remain a constant distance from. Use the Or operator when specifying multiple edges. For example: Button1.Anchor = AnchorStyles.Bottom Or _ AnchorStyles.Right Dock an object to one of the form’s edges Set the Dock property of the object, and specify the edge you want the object to be attached to. For example: PictureBox1.Dock = DockStyle.Top Specify the startup form in a project Click the Properties command on the Project menu to open the Project Designer. For a Windows Forms Application project, you can specify any form in your project as the startup form by clicking the form name in the Startup Form list box. Create a Visual Basic program with no user interface (or only a command line interface) Create a console application project by clicking the New Project com- mand on the File menu, clicking the Console Application template, and clicking OK. You then add the program code to one or more modules, not forms, and execution begins with a procedure named Sub Main. T o Do th is 373 Chapter 15 Adding Graphics and Animation Effects After completing this chapter, you will be able to:  Use the System.Drawing namespace to add graphics to your forms.  Create animation effects on your forms.  Expand or shrink objects on a form at run time.  Change the transparency of a form. For many developers, adding artwork and special effects to an application is the most exciting—and addictive—part of programming. Fortunately, creating impressive and useful graphical effects with Microsoft Visual Basic 2008 is both satisfying and easy. In this chapter, you’ll learn how to add a number of visually interesting features to your pro- grams. You’ll learn how to create artwork on a form using the System.Drawing namespace, how to create simple animation effects by using PictureBox and Timer controls, and how to expand or shrink objects at run time by using the Height and Width properties. You’ll also learn how to change the transparency of the form, and change a form’s background image and color. When you’ve fi nished, you’ll have many of the skills you need to create a visually exciting user interface. What will you be able to do on your own? This is the point when your imagination takes over. One of my favorite results is from a reader of a previous version of this book who used what he had learned about Visual Basic and graphics to build his own electrocardio- graph machine, complete with analog circuitry and a Windows form displaying digital data from the homemade EKG. If this isn’t your idea of fun, you might more modestly decide to enhance your application’s start page so that it contains custom artwork and visual effects—perhaps in combination with one or more digital photographs loaded into picture box objects on a form. Even game programmers can have some serious fun using graphics in Visual Basic and Microsoft Visual Studio. However, if you’re planning on creating the next version of Microsoft Zoo Tycoon or Microsoft Halo, you had better plan for much more than visual output. Modern video games contain huge libraries of objects and complex formulas for rendering graphical images that go well beyond the scope of this book. But that still leaves a lot of room for experimentation and fun! 374 Part III Designing the User Interface Adding Artwork by Using the System.Drawing Namespace Adding ready-made artwork to your programs is easy in Visual Basic. Throughout this book, you’ve experimented with adding bitmaps and icons to a form by using picture box objects. Now you’ll learn how to create original artwork on your forms by using the GDI+ functions in the System.Drawing namespace, an application programming interface (API) provided by the Microsoft .NET Framework for creating two-dimensional vector graphics, imaging, and typography within the Windows operating system. The effects that you create can add color, shape, and texture to your forms. Using a Form’s Coordinate System The fi rst thing to learn about creating graphics is the layout of the form’s predefi ned coordi- nate system. In Visual Basic, each form has its own coordinate system. The coordinate system’s starting point, or origin, is the upper-left corner of a form. The default coordinate system is made up of rows and columns of device-independent picture elements, or pixels, which rep- resent the smallest points that you can locate, or address, on a Visual Basic form. In the Visual Basic coordinate system, rows of pixels are aligned to the x-axis (horizontal axis), and columns of pixels are aligned to the y-axis (vertical axis). You defi ne locations in the coordinate system by identifying the intersection of a row and a column with the nota- tion (x, y). The (x, y) coordinates of the upper-left corner of a form are always (0, 0). The following illustration shows how the location for a picture box object on the form is described in the Visual Basic coordinate system: x-axis y-axis (0,0) x=128 pixels y=56 pixels (128,56) Chapter 15 Adding Graphics and Animation Effects 375 Visual Basic works along with your computer’s video display driver software to determine how pixels are displayed on the form and how shapes such as lines, rectangles, curves, and circles are displayed. Occasionally, more than one pixel is turned on to display a particular shape, such as the line drawing shown in the following illustration. The logic that handles this type of rendering isn’t your responsibility—it’s handled by your display adapter and the drawing routines in the GDI+ graphics library. The following illustration shows a zoomed-in view of the distortion or jagged edges you sometimes see in Visual Basic and Windows applications: Pixel (0,0) Pixel (7,4) Pixel (15,10) The System.Drawing.Graphics Class The System.Drawing namespace includes numerous classes for creating artwork and special effects in your programs. In this section, you’ll learn a little about the System.Drawing.Graphics class, which provides methods and properties for drawing shapes on your forms. You can learn about the other classes by referring to the Visual Studio documentation. Whether you’re creating simple illustrations or building complex drawings, it’s important to be able to render many of the standard geometric shapes in your programs. The follow- ing table lists several of the fundamental drawing shapes and the methods you use in the System.Drawing.Graphics class to create them. Shape Method Description Line DrawLine Simple line connecting two points. Rectangle DrawRectangle Rectangle or square connecting four points. Arc DrawArc Curved line connecting two points (a portion of an ellipse). Circle/Ellipse DrawEllipse Elliptical shape that is “bounded” by a rectangle. Polygon DrawPolygon Complex shape with a variable number of points and sides (stored in an array). Curve DrawCurve A curved line that passes through a variable number of points (stored in an array); complex curves called cardinal splines can also be drawn with this method. Bézier splines DrawBezier A curve drawn by using four points. (Points two and three are “control” points.) S h ap e Met h o d D escr i pt i on 376 Part III Designing the User Interface In addition to the preceding methods, which create empty or “non-fi lled” shapes, there are several methods for drawing shapes that are fi lled with color. These methods usually have a “Fill” prefi x, such as FillRectangle, FillEllipse, and FillPolygon. When you use a graphics method in the System.Drawing.Graphics class, you need to create a Graphics object in your code to represent the class and either a Pen or Brush object to indicate the attributes of the shape you want to draw, such as line width and fi ll color. The Pen object is passed as one of the arguments to the methods that aren’t fi lled with color. The Brush object is passed as an argument when a fi ll color is desired. For example, the fol- lowing call to the DrawLine method uses a Pen object and four integer values to draw a line that starts at pixel (20, 30) and ends at pixel (100, 80). The Graphics object is declared by using the name GraphicsFun, and the Pen object is declared by using the name PenColor. Dim GraphicsFun As Graphics Dim PenColor As New Pen(Color.Red) GraphicsFun = Me.CreateGraphics GraphicsFun.DrawLine(PenColor, 20, 30, 100, 80) The syntax for the DrawLine method is important, but also note the three lines above it, which are required to use a method in the System.Drawing.Graphics class. You must create variables to represent both the Graphics and Pen objects, and the Graphics variable needs to be instantiated by using the CreateGraphics method for the Windows form. Note that the System.Drawing.Graphics namespace is included in your project automatically—you don’t need to include an Imports statement in your code to reference the class. Using the Form’s Paint Event If you test the previous DrawLine method in a program, you’ll notice that the line you created lasts, or persists, on the form only as long as nothing else covers it up. If a dialog box opens on the form momentarily and covers the line, the line is no longer visible when the entire form is visible again. The line also disappears if you minimize the form window and then maximize it again. To address this shortcoming, you need to place your graphics code in the form’s Paint event procedure so that each time the form is refreshed, the graphics are repainted, too. In the following exercise, you’ll create three shapes on a form by using the form’s Paint event procedure. The shapes you draw will continue to persist even if the form is covered or minimized. Create line, rectangle, and ellipse shapes 1. Start Visual Studio, and create a new Windows Forms Application project named My Draw Shapes. 2. Resize the form so that it’s longer and wider than the default form size. Chapter 15 Adding Graphics and Animation Effects 377 You’ll need a little extra space to create the graphics shapes. You won’t be using any Toolbox controls, however. You’ll create the shapes by placing program code in the form’s Form1_Paint event procedure. 3. Set the Text property of Form1 to “Draw Shapes”. 4. Click the View Code button in Solution Explorer to display the Code Editor. 5. In the Class Name list box, click Form1 Events. Form1 Events is the list of events in your project associated with the Form1 object. 6. In the Method Name list box, click the Paint event. 7. The Form1_Paint event procedure appears in the Code Editor. This event procedure is where you place code that should be executed when Visual Basic refreshes the form. 8. Type the following program code: 'Prepare GraphicsFun variable for graphics calls Dim GraphicsFun As Graphics GraphicsFun = Me.CreateGraphics 'Use a red pen color to draw a line and an ellipse Dim PenColor As New Pen(Color.Red) GraphicsFun.DrawLine(PenColor, 20, 30, 100, 80) GraphicsFun.DrawEllipse(PenColor, 10, 120, 200, 160) 'Use a green brush color to create a filled rectangle Dim BrushColor As New SolidBrush(Color.Green) GraphicsFun.FillRectangle(BrushColor, 150, 10, 250, 100) 'Create a blue cardinal spline curve with four points Dim Points() As Point = {New Point(358, 280), _ New Point(300, 320), New Point(275, 155), New Point(350, 180)} For tension As Single = 0 To 2.5 Step 0.5 GraphicsFun.DrawCurve(Pens.DodgerBlue, Points, tension) Next This sample event procedure draws four graphic shapes on your form: a red line, a red ellipse, a green-fi lled rectangle, and a blue cardinal spline (a complex curve made up of fi ve lines). To enable graphics programming, the routine declares a variable named GraphicsFun in the code and uses the CreateGraphics method to activate or instantiate the variable. The PenColor variable of type Pen is used to set the drawing color in the line and ellipse, and the BrushColor variable of type SolidBrush is used to set the fi ll color in the rectangle. These examples are obviously just the tip of the graphics library iceberg—there are many more shapes, colors, and variations that you can create by using the methods in the System.Drawing.Graphics class. Tip The complete Draw Shapes program is located in the c:\vb08sbs\chap15\draw shapes folder. 378 Part III Designing the User Interface 9. Click the Start Debugging button on the Standard toolbar to run the program. Visual Basic loads the form and executes the form’s Paint event. Your form looks like this: 10. Minimize the form, and then restore it again. The form’s Paint event is executed again, and the graphics shapes are refreshed on the form. 11. Click the Close button to end the program. 12. Click the Save All button on the Standard toolbar to save the project, and specify the c:\vb08sbs\chap15 folder as the location. Now you’re ready to move on to some simple animation effects. Adding Animation to Your Programs Displaying bitmaps and drawing shapes adds visual interest to a program, but for program- mers, the king of graphical effects has always been animation. Animation is the simulation of movement produced by rapidly displaying a series of related images on the screen. Real animation involves moving objects programmatically, and it often involves changing the size or shape of the images along the way. In this section, you’ll learn how to add simple animation to your programs. You’ll learn how to update the Top and Left properties of a picture box, control the rate of animation by using a timer object, and sense the edge of your form’s window. Chapter 15 Adding Graphics and Animation Effects 379 Moving Objects on the Form In Visual Basic 6, a special method named Move allows you to move objects in the coordinate system. The Move method is no longer supported by Visual Basic 2008 controls. However, you can use the properties and method shown in the following table instead. Keyword Description Left This property can be used to move an object horizontally (left or right). Top This property can be used to move an object vertically (up or down). Location This property can be used to move an object to the specifi ed location. SetBounds This method sets the boundaries of an object to the specifi ed location and size. The following sections discuss how you can use the Left, Top, and Location properties to move objects. To move an object in a horizontal direction, use the Left property, which uses the syntax object.Left = horizontal where object is the name of the object on the form that you want to move, and horizontal is the new horizontal, or x-axis, coordinate of the left edge of the object, measured in pixels. For example, the following program statement moves a picture box object to a location 300 pixels to the right of the left window edge: PictureBox1.Left = 300 To move a relative distance to the right or left, you would add or subtract pixels from the current Left property setting. For example, to move an object 50 pixels to the right, you add 50 to the Left property, as follows: PictureBox1.Left = PictureBox1.Left + 50 In a similar way, you can change the vertical location of an object on a form by setting the Top property, which takes the syntax object.Top = vertical where object is the name of the object on the form that you want to move, and vertical is the new vertical, or y-axis, coordinate of the top edge of the object, measured in pixels. For example, the following program statement moves a picture box object to a location 150 pix- els below the window’s title bar: PictureBox1.Top = 150 Ke y word D escri p tion 380 Part III Designing the User Interface Relative movements down or up are easily made by adding or subtracting pixels from the current Top property setting. For example, to move 30 pixels in a downward direction, you add 30 to the current Top property, as follows: PictureBox1.Top = PictureBox1.Top + 30 The Location Property To move an object in both vertical and horizontal directions, you can use a combination of the Left and Top property settings. For example, to relocate the upper-left corner of a picture box object to the (x, y) coordinates (300, 200), you enter the following program code: PictureBox1.Left = 300 PictureBox1.Top = 200 However, the designers of Visual Studio don’t recommend using two program statements to relocate an object if you plan to make numerous object movements in a program (for example, if you plan to move an object hundreds or thousands of times during an elaborate animation effect). Instead, you should use the Location property with the syntax object.Location = New Point(horizontal, vertical) where object is the name of the object, horizontal is the horizontal x-axis coordinate, vertical is the vertical y-axis coordinate, and Point is a structure identifying the pixel location for the upper-left corner of the object. For example, the following program statement moves a picture box object to an (x, y) coordinate of (300, 200): PictureBox1.Location = New Point(300, 200) To perform a relative movement using the Location property, the Location.X and Location.Y properties are needed. For example, the program statement PictureBox1.Location = New Point(PictureBox1.Location.X - 50, _ PictureBox1.Location.Y - 40) moves the picture box object 50 pixels left and 40 pixels up on the form. Although this construction seems a bit unwieldy, it’s the recommended way to relocate objects in relative movements on your form at run time. Creating Animation by Using a Timer Object The trick to creating animation in a program is placing one or more Location property updates in a timer event procedure so that at set intervals the timer causes one or more objects to drift across the screen. In Chapter 7, “Using Loops and Timers,” you learned how to use a timer ob- ject to update a simple clock utility every second so that it displayed the correct time. When [...]... them These capabilities have been enhanced in Microsoft Visual Studio 20 08 In this chapter, you’ll experiment with both types of inheritance You’ll learn how to integrate existing forms into your projects by using the Inheritance Picker dialog box that is part of Visual Studio 20 08, and you’ll learn how to create your own classes and derive new ones from them by using the Inherits statement With these... me, you’ll find that creating classes and inheriting them is quite simple in Visual Basic 20 08 and that you can accomplish a lot of useful work by adding just a few lines of program code to your projects Understanding object-oriented terminology will also help you make sense of some of the advanced features of Visual Basic 20 08, such as Language Integrated Query (LINQ), anonymous types, extension methods,... building block in Visual Basic programs, you might very well ask how new classes are created and how these new classes might be inherited down the road by subsequently derived classes To ponder these possibilities, I’ll devote the remainder of this chapter to discussing the syntax for creating classes in Visual Basic 20 08 and introducing how these user-defined classes might be inherited later by still more... object-oriented programming features, experts say that it lags behind the “true” OOP languages, such as Microsoft Visual C++, because it lacks inheritance, a mechanism that allows one class to acquire the interface and behavior characteristics of another class Beginning with Microsoft Visual Basic NET 2002, the Visual Basic language and IDE have supported inheritance, which means that you can build one form in... methods Derive new classes from base classes by using the Inherits statement An important skill for virtually all professional software developers today is the ability to understand and utilize object-oriented programming (OOP) techniques The changes associated with OOP have been gaining momentum in recent versions of Visual Basic Although Microsoft Visual Basic 6 offers several object-oriented programming... code in the Button2_Click event procedure: Me.Opacity = 1 This line restores the opacity to 100 percent 388 Part III Designing the User Interface 8 Click the Save All button, and save the project in the c:\vb08sbs\chap15 folder Tip The complete Transparent Form program is located in the c:\vb08sbs\chap15\ transparent form folder 9 Click the Start Debugging button to run the program 10 Click the Set... of the Earth icon by 15 pixels each time the user clicks the picture box If you stretch your imagination a little, watching the effect makes you feel like you’re approaching Earth in a spaceship 386 Part III Designing the User Interface 8 Click the Save All button, and then save the project in the c:\vb08sbs\chap15 folder Tip The complete Zoom In program is located in the c:\vb08sbs\chap15\zoom in... somewhat general 8 Type Person.vb in the Name box, and then click Add Chapter 16 Inheriting Forms and Creating Base Classes 401 Visual Studio opens a blank class module in the Code Editor and lists a file named Person.vb in Solution Explorer for your project, as shown here: Now you’ll type the definition of your class in the class module and learn a few new Visual Basic keywords You’ll follow four steps: declare... class Step 1: Declare class variables Below the Public Class Person program statement, type the following variable declarations: Private Name1 As String Private Name2 As String Here you declare two variables that will be used exclusively within the class module to store the values for two string property settings I’ve declared the variables by using the Private keyword because, by convention, Visual Basic. .. create a second copy of a dialog box in a project Inherit a simple dialog box 1 Start Visual Studio, and create a new Visual Basic Windows Forms Application project named My Form Inheritance 2 Display the form in the project, and use the Button control to add two button objects at the bottom of the form, positioned side by side 3 Change the Text properties of the Button1 and Button2 buttons to “OK” and . impressive and useful graphical effects with Microsoft Visual Basic 20 08 is both satisfying and easy. In this chapter, you’ll learn how to add a number of visually interesting features to your pro- grams Visual Basic and Microsoft Visual Studio. However, if you’re planning on creating the next version of Microsoft Zoo Tycoon or Microsoft Halo, you had better plan for much more than visual output form is described in the Visual Basic coordinate system: x-axis y-axis (0,0) x=1 28 pixels y=56 pixels (1 28, 56) Chapter 15 Adding Graphics and Animation Effects 375 Visual Basic works along with

Ngày đăng: 12/08/2014, 20:22

Từ khóa liên quan

Mục lục

  • Part III: Designing the User Interface

    • Chapter 15: Adding Graphics and Animation Effects

      • Adding Artwork by Using the System.Drawing Namespace

        • Using a Form’s Coordinate System

        • The System.Drawing.Graphics Class

        • Using the Form’s Paint Event

        • Adding Animation to Your Programs

          • Moving Objects on the Form

          • The Location Property

          • Creating Animation by Using a Timer Object

          • Expanding and Shrinking Objects While a Program Is Running

          • One Step Further: Changing Form Transparency

          • Chapter 15 Quick Reference

          • Chapter 16: Inheriting Forms and Creating Base Classes

            • Inheriting a Form by Using the Inheritance Picker

            • Creating Your Own Base Classes

              • Sidebar: Nerd Alert

              • Adding a New Class to Your Project

              • One Step Further: Inheriting a Base Class

                • Sidebar: Further Experiments with Object-Oriented Programming

                • Chapter 16 Quick Reference

                • Chapter 17: Working with Printers

                  • Using the PrintDocument Class

                    • Printing Text from a Text Box Object

                    • Printing Multipage Text Files

                    • One Step Further: Adding Print Preview and Page Setup Dialog Boxes

Tài liệu cùng người dùng

Tài liệu liên quan