Beginning Microsoft Visual Basic 2008 phần 7 docx

92 355 0
Beginning Microsoft Visual Basic 2008 phần 7 docx

Đ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 15: Programming Custom Graphics 519 Using System Colors Now you know that you can choose colors from a list of possibilities as well as define your own. The final thing you need to learn about colors is the idea of system colors. When using Windows, the user has the ability to define all of the colors that are used for things like buttons, menus, captions, and so on. If you ’ re building the UI for your own controls, it ’ s reasonable to assume that from time to time you ’ ll need to know what these colors are so that your controls have the same look and feel as the existing controls in the system. System colors are exposed through the System.Drawing.SystemColors class. If you want to find a list of all the system colors, look in the MSDN documentation under System.Drawing.SystemColors class. Alternatively, use IntelliSense when in the Code Editor or the Object Browser. In this Try It Out, you ’ ll add a button to the control palette that is the same as the menu bar. Try It Out Adding System Colors 1. Open the Code Editor for ColorPalette.Designer.vb . Find the constructor and add the following highlighted code: Public Sub New() ‘ This call is required by the Windows Form Designer. InitializeComponent() ‘ Add any initialization after the InitializeComponent() call. ‘Add the colors AddColor(Color.Black) AddColor(Color.White) AddColor(Color.Red) AddColor(Color.Blue) AddColor(Color.Green) AddColor(Color.Gray) AddColor(Color.DarkRed) AddColor(Color.DarkBlue) AddColor(Color.DarkGreen) AddColor(Color.DarkGray) AddColor(Color.FromArgb(208, 112, 222)) AddColor(Drawing.SystemColors.MenuBar) End Sub 2. Run the project. You should see a new color that matches the menu bar color. c15.indd 519c15.indd 519 4/1/08 6:38:54 PM4/1/08 6:38:54 PM Chapter 15: Programming Custom Graphics 520 Using Different Tools Now that you have successfully cracked the nut of drawing filled circles on the page, turn your attention to building the other tools that you can use to put your applications together. In the next Try It Out, you add a menu that lets you select the tool you want. If you need a refresher on how to use the Visual Basic 2008 Menu Designer, refer to Chapter 9 . Try It Out Adding a Tools Menu 1. Open the Forms Designer for Form1 and change the Anchor property for Canvas to Bottom, Right, Left. 2. Click the title bar of the form and then resize the form so that there is enough room for a MenuStrip control at the top. 3. Drag a MenuStrip control onto the top of the form; then right - click MenuStrip1 and choose Insert Standard Items from the context menu to have the standard menus inserted. 4. Resize the form if necessary so that the Canvas control is just under the menu. Then click the Canvas control and change the Anchor property to Top, Bottom, Right, Left. 5. Click the Tools menu on the MenuStrip and then click in the white Type Here box that appears at the bottom of the Tools menu and enter Ci & rcle . Using the Properties window set the Checked property to True and the CheckOnClick property to Tr ue . 6. In the new Type Here box at the bottom, enter & Hollow Circle , and in the Properties window, set the CheckOnClick property to True . You can see the results of these steps in Figure 15 - 7 . Figure 15-7 c15.indd 520c15.indd 520 4/1/08 6:38:55 PM4/1/08 6:38:55 PM Chapter 15: Programming Custom Graphics 521 Implementing Hollow Circle Up until now, you have used a solid circle as the graphics pen to perform the drawing on your form. In this Try It Out, you ’ ll be implementing the functionality to use the hollow circle graphics pen. You ’ ll also be adding the necessary code that will allow you to select which pen you want to use from the Tools menu. Try It Out Implementing Hollow Circle 1. The first thing you need to do is change the GraphicTools enumeration defined in the PaintCanvas class to include the hollow circle tool. Open the Code Editor for PaintCanvas and add the following highlighted code to the enumeration: Public Class PaintCanvas ‘Public enumerations Public Enum GraphicTools As Integer CirclePen = 0 HollowCirclePen = 1 End Enum 2. Switch to the Code Editor for Form1. In the Class Name combo box, select CircleToolStripMenuItem , and then select the Click event in the Method Name combo box. Add the following highlighted code to the Click event handler: Private Sub CircleToolStripMenuItem_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles CircleToolStripMenuItem.Click ‘Set the tool Canvas.GraphicTool = PaintCanvas.GraphicTools.CirclePen ‘Uncheck the Hollow Circle menu item HollowCircleToolStripMenuItem.Checked = False End Sub 3. Select HollowCircleToolStripMenuItem in the Class Name combo box and the Click event in the Method Name combo box. Add the following highlighted code: Private Sub HollowCircleToolStripMenuItem_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles HollowCircleToolStripMenuItem.Click ‘Set the tool Canvas.GraphicTool = PaintCanvas.GraphicTools.HollowCirclePen ‘Uncheck the Circle menu item CircleToolStripMenuItem.Checked = False End Sub c15.indd 521c15.indd 521 4/1/08 6:38:55 PM4/1/08 6:38:55 PM Chapter 15: Programming Custom Graphics 522 4. It only makes sense that, since you ’ ve implemented a menu, you should add code to the Exit menu item. Select exitToolStripMenuItem in the Class Name combo box and the Click event in the Method Name combo. Then add the following highlighted code to the Click event handler: Private Sub exitToolStripMenuItem_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles exitToolStripMenuItem.Click ‘Close the application Me.Close() End Sub 5. Open the Code Editor for PaintCanvas again and modify the Select Case GraphicTool statement in the DoMousePaint method as follows: ‘What tool are you using? Select Case GraphicTool ‘CirclePen Case GraphicTools.CirclePen ‘Create a new graphics circle Dim objGraphicsCircle As New GraphicsCircle() ‘Set the point for drawing objGraphicsCircle.SetPoint(e.X, e.Y, GraphicSize, _ objColor, True) ‘Store this for addition objGraphicsItem = objGraphicsCircle ‘HollowCirclePen Case GraphicTools.HollowCirclePen ‘Create a new graphics circle Dim objGraphicsCircle As New GraphicsCircle() ‘Set the point for drawing objGraphicsCircle.SetPoint(e.X, e.Y, GraphicSize, _ objColor, False) ‘Store this for addition objGraphicsItem = objGraphicsCircle End Select c15.indd 522c15.indd 522 4/1/08 6:38:55 PM4/1/08 6:38:55 PM Chapter 15: Programming Custom Graphics 523 6. Next, you need to change the GraphicsCircle class itself so that it knows when to draw a filled circle and when to draw a hollow circle. Open the Code Editor for GraphicsCircle and add the following highlighted code to the Draw method: Public Overrides Sub Draw(ByVal graphics As System.Drawing.Graphics) If IsFilled = True Then ‘Create a new pen Dim objSolidBrush As New SolidBrush(Me.Color) ‘Draw the circle graphics.FillEllipse(objSolidBrush, Me.Rectangle) Else ‘Create a pen Dim pen As New Pen(Me.Color) ‘Use DrawEllipse instead Dim objRectangle As Rectangle = Me.Rectangle objRectangle.Inflate(-1, -1) graphics.DrawEllipse(pen, objRectangle) End If End Sub 7. Finally, run the program. You should be able to select a new graphic tool from the menu and draw both filled and hollow circles, as shown in Figure 15 - 8 . Figure 15-8 How It Works When the menu options are selected, Click events get fired. You can respond to these messages and set the GraphicsTool property on the PaintCanvas control to a new mode. When you change the mode, you also need to change the check mark on the menu. The currently selected menu item will be automatically checked, but you need to uncheck the menu item that isn ’ t selected. You do this by setting the Checked property of the opposite menu item to False . c15.indd 523c15.indd 523 4/1/08 6:38:55 PM4/1/08 6:38:55 PM Chapter 15: Programming Custom Graphics 524 Private Sub HollowCircleToolStripMenuItem_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles HollowCircleToolStripMenuItem.Click ‘Set the tool Canvas.GraphicTool = PaintCanvas.GraphicTools.HollowCirclePen ‘Uncheck the Circle menu item CircleToolStripMenuItem.Checked = False End Sub Irrespective of the mode used, PaintCanvas.DoMousePaint still gets called whenever the mouse draws on the control. However, you do need to accommodate the new tool by changing the Select Case GraphicTool statement to look for HollowCirclePen as well as CirclePen . Depending on which is selected, you pass True (filled) or False (not filled) through to SetPoint : ‘What tool are you using? Select Case GraphicTool ‘CirclePen Case GraphicTools.CirclePen ‘Create a new graphics circle Dim objGraphicsCircle As New GraphicsCircle() ‘Set the point for drawing objGraphicsCircle.SetPoint(e.X, e.Y, GraphicSize, _ objColor, True) ‘Store this for addition objGraphicsItem = objGraphicsCircle ‘HollowCirclePen Case GraphicTools.HollowCirclePen ‘Create a new graphics circle Dim objGraphicsCircle As New GraphicsCircle() ‘Set the point for drawing objGraphicsCircle.SetPoint(e.X, e.Y, GraphicSize, _ objColor, False) ‘Store this for addition objGraphicsItem = objGraphicsCircle End Select In GraphicsCircle itself, choosing whether to use the FillEllipse method to draw a filled circle or use the DrawEllipse method for a hollow one is a simple determination. The only wrinkle you have to contend with is DrawEllipse ; the width and height of the bounding rectangle have to be one pixel smaller than those used for FillEllipse . This is due to an idiosyncrasy in the way the Windows graphics subsystem works. You ’ ll often find when working with graphics features that you have to experiment a little! c15.indd 524c15.indd 524 4/1/08 6:38:56 PM4/1/08 6:38:56 PM Chapter 15: Programming Custom Graphics 525 Public Overrides Sub Draw(ByVal graphics As System.Drawing.Graphics) If IsFilled = True Then ‘Create a new pen Dim objSolidBrush As New SolidBrush(Me.Color) ‘Draw the circle graphics.FillEllipse(objSolidBrush, Me.Rectangle) Else ‘Create a pen Dim pen As New Pen(Me.Color) ‘Use DrawEllipse instead Dim objRectangle As Rectangle = Me.Rectangle objRectangle.Inflate(-1, -1) graphics.DrawEllipse(pen, objRectangle) End If End Sub Now that you ’ ve learned the basics of building user controls that support their own user interface, take a look at the image - handling capabilities in Visual Basic 2008. Working with Images The .NET Framework has very good support for loading and saving common image formats. In particular, you ’ re able to load images of these types: .bmp : The standard Windows bitmap format .gif : The standard lossless common Internet file format for graphic files and small images .jpeg or .jpg : The standard lossy common Internet file format for photo - quality images .png : The competitor to .gif that doesn ’ t have the tricky licensing implications .tiff : The standard file format for storing and manipulated scanned documents .wmf / .emf : The standard file formats for saving Windows Metafiles .ico : The standard file format for program icons .exif : The preferred file format for storage used internally with digital cameras Prior to .NET, developers wanting to work with the most common Internet file formats (namely, .gif and .jpeg ) had to buy third - party libraries. Now, support is built directly into the .NET Framework, so from day one you can start building applications that can handle these formats. What ’ s more surprising is that the .NET Framework also supports saving these files. This allows you to load a .gif file and save ❑ ❑ ❑ ❑ ❑ ❑ ❑ ❑ c15.indd 525c15.indd 525 4/1/08 6:38:56 PM4/1/08 6:38:56 PM Chapter 15: Programming Custom Graphics 526 it as, say, a .bmp or .png file. There are two ways in which you can use images with Visual Basic 2008. First, you can use the PictureBox control that you can find in the Visual Studio 2008 Toolbox. This is a control that you place on a form, set a reference to an image, either at design time or runtime and it deals with painting itself. This is a quick way of getting a fixed image on a form. The second way in which you can use images is inside your owner - draw controls. In the following exercise, you ’ ll see how you can tweak WroxPaint so that, rather than drawing on a dull, white background, you ’ re actually drawing on an image you load. Drawing Images The property on the control takes a System.Drawing.Image object. In addition to using the Image class with PictureBox and a few other controls in the .NET Framework, you can also use it with your own owner - draw controls. In the next Try It Out, you start by providing a way for your owner - drawn controls to display an image loaded from one of the supported image formats. Try It Out Setting the BackgroundImage 1. Open the Designer for Form1. Using the Toolbox drag an OpenFileDialog control onto the form. Set the Name property of the control to dlgFileOpenBackground . 2. Switch to the Code Editor for Form1. You are going to wire up the Open menu item under the File menu to show the Open File dialog box. Select openToolStripMenuItem in the Class Name combo box and then select the Click event in the Method Name combo box. Add the following highlighted code to the Click event handler: Private Sub openToolStripMenuItem_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles openToolStripMenuItem.Click ‘Set the open file dialog properties With dlgFileOpenBackground .Filter = “Image files (*.gif,*.jpg,*.jpeg,*.bmp,*.wmf,*.png)” & _ “|*.gif;*.jpg;*.jpeg;*.bmp;*.wmf;*.png|All files (*.*)|*.*” .FilterIndex = 1 .Title = “Open Picture Files” End With ‘Show the dialog If dlgFileOpenBackground.ShowDialog() = DialogResult.OK Then ‘Create a new image that references the file Dim backgroundImage As Image = _ Image.FromFile(dlgFileOpenBackground.FileName) ‘Set the background of the canvas Canvas.BackgroundImage = backgroundImage End If End Sub c15.indd 526c15.indd 526 4/1/08 6:38:56 PM4/1/08 6:38:56 PM Chapter 15: Programming Custom Graphics 527 3. Run the project. Select File Open from the menu and find a .bmp , .jpg , .jpeg , or .gif file somewhere on your computer. (If you try to open a file from the network, you may get a security exception.) The image will be displayed as shown in Figure 15 - 9 . Figure 15-9 How It Works If you said, “ But I didn ’ t do anything! ” you ’ re quite right — you didn ’ t have to write any code to support the background image. By default, the Control class from which UserControl is ultimately derived already supports a BackgroundImage property, and you ’ ve set this to the image you loaded. Therefore, the base class is dealing with drawing the image. The loading is actually done with the shared FromFile method on the Image class. This method is the easiest way of loading a file from a disk: ‘Show the dialog If dlgFileOpenBackground.ShowDialog() = DialogResult.OK Then ‘Create a new image that references the file Dim backgroundImage As Image = _ Image.FromFile(dlgFileOpenBackground.FileName) ‘Set the background of the canvas Canvas.BackgroundImage = backgroundImage End If Finally, when you ’ re actually drawing on the image, you may find the paint process sluggish. This is because the control is spending a lot of time drawing the image onto the control, and this slows everything down. Try using a smaller image, or consider this Try It Out an illustration of how to manipulate images rather than a neat paint package! c15.indd 527c15.indd 527 4/1/08 6:38:57 PM4/1/08 6:38:57 PM Chapter 15: Programming Custom Graphics 528 Scaling Images If you resize the form, you ’ ll notice that the image is actually tiled. More importantly, if you make the control too small to accommodate the whole image, the sides of the image are clipped. What you want is for the image to be scaled so that it fits the control exactly. Therefore, in the next Try It Out, you take over control of drawing the background image from the base Control class and provide a new implementation of the BackgroundImage property. Try It Out Drawing the Image Yourself 1. Open the Code Editor for PaintCanvas . 2. Rather than adding your code to draw the image to the Paint method, you ’ re going to work with a different event called OnPaintBackground . This method is called before the Paint method. Add the following code: Protected Overrides Sub OnPaintBackground( _ ByVal e As System.Windows.Forms.PaintEventArgs) ‘Paint the invalid region with the background brush Dim backgroundBrush As New SolidBrush(BackColor) e.Graphics.FillRectangle(backgroundBrush, e.ClipRectangle) ‘Paint the image If Not BackgroundImage Is Nothing Then ‘Find our client rectangle Dim clientRectangle As New Rectangle(0, 0, Width, Height) ‘Draw the image e.Graphics.DrawImage(BackgroundImage, clientRectangle) End If End Sub 3. Now select (PaintCanvas Events) in the Class Name combo box and the Resize event in the Method Name combo box. Add the following highlighted code to the Resize event handler: Private Sub PaintCanvas_Resize(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Resize ‘Invalidate the control Me.Invalidate() End Sub c15.indd 528c15.indd 528 4/1/08 6:38:57 PM4/1/08 6:38:57 PM [...]... 6:38:59 PM 16 Accessing Databases Most applications manipulate data in some way Visual Basic 2008 applications often manipulate data that come from relational databases To do this, your application needs to interface with relational database software such as Microsoft Access, Microsoft SQL Server, Oracle, or Sybase Visual Studio 2008 provides the data access tools and wizards to connect to these databases... objects in Microsoft Access are a hybrid of two types of objects in SQL Server: views and stored procedures Using database query objects can make your Visual Basic 2008 code simpler, because you have fewer complex SQL queries included in your code They can also make your programs faster, because database engines can compile queries when you create them, whereas the SQL code in a Visual Basic 2008 program... 16 -7 was generated The next section discusses the basic data access components that are needed in Windows Forms to display data Since you have been using Microsoft Access in your examples here, the focus is on the data access components provided in Visual Studio 2008 that assist you in accessing the data in an Access database Data Access Components There are three main data access components in Visual. .. Choose Data Source dialog box, select Microsoft Access Database File in the Data Source list and then click the Continue button 7 In the Add Connection dialog box, click the Browse button and navigate to the samples folder for Microsoft office By default, this will be in the folder C:\Program Files \Microsoft Office\Office11\Samples\ for a default installation of Microsoft Office 2003 (11 is the version... sample databases were installed when you installed Microsoft Access or Microsoft Office You’ll create this query and then view the SQL SELECT statement that gets generated by Access Try It Out 1 Creating a Customer Query For Access 2000: Open Microsoft Access and click the Open icon on the toolbar In the Open dialog box, navigate to C:\Program Files \Microsoft Office\Office11\Samples\ and open Northwind.mdb... users work with and display data You will be writing Visual Basic 2008 applications to do this, so the only database objects you’re really concerned about at the moment are tables and queries Tables A table contains a collection of data, which is represented by one or more columns and one or more rows of data Columns are typically referred to as fields in Microsoft Access, and the rows are referred to as... detail in Chapter 17 545 c16.indd 545 4/1/08 6:39:28 PM Chapter 16: Accessing Databases Data Binding Data binding means taking data referenced by your BindingSource and binding it to a control In other words, the control will receive its data from your data access components, and the data will be automatically displayed in the control for the user to see and manipulate In Visual Basic 2008, most controls... data binding in Windows Forms ❑ Use the data access wizards in Visual Studio 2008 Note that in order to work through the exercises in this chapter, you will need Microsoft Access 2000 or later What Is a Database? A database consists of one or more large, complex files that store data in a structured format The database engine, in your case Microsoft Access, manages the file or files and the data within... click the Browse button and navigate to the samples folder for Microsoft office By default, this will be in the folder C:\Program Files \Microsoft Office\Office11\Samples\ for a default installation of Microsoft Office 2003 (11 is the version and will change based on your version of Office) Select the Northwind.mdb database in the Select Microsoft Access Database File dialog box and click the Open button... those files c16.indd 535 4/1/08 6:39:25 PM Chapter 16: Accessing Databases Microsoft Access Objects A Microsoft Access database file, which has the extension mdb, contains tables, queries, forms, reports, pages, macros, and modules, which are referred to as database objects That’s a lot of information in one large file, but Microsoft Access manages this data quite nicely Forms, reports, pages, macros, . are two ways in which you can use images with Visual Basic 2008. First, you can use the PictureBox control that you can find in the Visual Studio 2008 Toolbox. This is a control that you place. that you ’ ve learned the basics of building user controls that support their own user interface, take a look at the image - handling capabilities in Visual Basic 2008. Working with Images. how to manipulate images rather than a neat paint package! c15.indd 527c15.indd 5 27 4/1/08 6:38: 57 PM4/1/08 6:38: 57 PM Chapter 15: Programming Custom Graphics 528 Scaling Images If you

Ngày đăng: 09/08/2014, 14:21

Từ khóa liên quan

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

Tài liệu liên quan