Beginning Visual Basic 2005 phần 4 pps

84 314 0
Beginning Visual Basic 2005 phần 4 pps

Đ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

‘Show the Open dialog and if the user clicks the Open button, ‘load the file If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then End If End Sub 8. Now it’s time to use some of the prebuilt code snippets that come with Visual Studio 2005. Right click in the blank space between the If and End If statements and choose Insert Snippet from the context menu. In the drop-down menu that appears, double-click File System - Processing Drives, Folders, and Files and then scroll down the new list and double-click Read Text from a File. Your code should now look like this, and you’ll notice that the filename test.txt is high- lighted, indicating that this code needs to be changed: If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then Dim allText As String Try allText = My.Computer.FileSystem.ReadAllText(“test.txt”) Catch fileException As Exception Throw fileException End Try End If 9. Modify the code in the Try block as shown here: Try ‘Save the file name strFileName = OpenFileDialog1.FileName ‘Read the contents of the file allText = My.Computer.FileSystem.ReadAllText(strFileName) ‘Display the file contents in the TextBox txtFile.Text = allText Catch fileException As Exception 10. Now run your project, and once your form is displayed, click the Open button to have the Open File dialog box displayed. Notice the custom caption in the title bar of the dialog box; you speci- fied this in your code. If you click the Files of type: combo box, you will see two filters. Click the second filter to see all of the files in the current directory. 11. Now locate a text file on your computer and select it. Then click the Open button to have the file opened and the contents of that file placed in the text box on the form as shown in Figure 7-8. 12. For the final test, close your application and then start it again. Click the Open button on the form and notice that the Open File dialog box has opened in the last directory where you selected the last file from. How It Works Before displaying the Open File dialog box, you need to set some properties of OpenFileDialog1 so that the dialog box is customized for your application. You can do this with a With . . . End With statement. The With . . . End With statement allows you to make repeated references to a single object without hav- ing to specify the object name over and over. You specify the object name once on the line with the With statement and then add all references to the properties of that object before the End With statement. With OpenFileDialog1 218 Chapter 7 10_574019 ch07.qxd 9/16/05 9:21 PM Page 218 Figure 7-8 The first property that you set is the Filter property. This property enables you to define the filters that are displayed in the Files of type: combo box. When you define a file extension filter, you specify the fil- ter description followed by a vertical bar ( |) followed by the file extension. When you want the Filter property to contain multiple file extensions, as shown in the following code, you separate each file filter with a vertical bar as follows: .Filter = “Text files (*.txt)|*.txt|All files (*.*)|*.*” The next property that you set is the FilterIndex property. This property determines which filter is shown in the Files of type: combo box. The default value for this property is 1, which is the first filter: .FilterIndex = 1 Finally, you set the Title property. This is the caption that is displayed in the title bar of the dialog box: .Title = “Demo Open File Dialog” To show the Open File dialog box, you use the ShowDialog method. Remember that the ShowDialog method returns a DialogResult value, there are only two possible results, and you can compare the results from the ShowDialog method to Windows.Forms.DialogResult.OK and Windows.Forms .DialogResult.Cance l. If the user clicks the Open button in the dialog box, the ShowDialog method returns a value of OK, and if the user clicks the Cancel button, the ShowDialog method returns Cancel: If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then Next, you use the built-in code snippets provided by Visual Studio 2005 to simplify your programming tasks by using the Read Text from a File code snippet. This code snippet contains the necessary code to read the contents from a text file and to place those contents in a string variable. You modified the code snippet to retrieve the path and filename that the user has chosen in the Open File dialog box and set it in your strFileName variable. The path and filename are contained in the FileName property of the OpenFileDialog control: ‘Save the file name strFileName = OpenFileDialog1.FileName 219 Displaying Dialog Boxes 10_574019 ch07.qxd 9/16/05 9:21 PM Page 219 Next, you modify the code from the code snippet supplying the strFileName variable in the high- lighted section of code. This code will read the entire contents of the text file into the allText variable: ‘Read the contents of the file allText = My.Computer.FileSystem.ReadAllText(strFileName) The final line of code that you wrote takes the contents of the allText variable and sets it in the Text property of the TextBox control, thereby populating the text box with the contents of your text file: ‘Display the file contents in the TextBox txtFile.Text = allText There are many properties in the OpenFileDialog control that haven’t been covered in this chapter, and you should feel free to experiment on your own to see all of the possibilities that this dialog box has to offer. The SaveDialog Control Now that you can open a file with the OpenFileDialog control, take a look at the SaveFileDialog control so that you can save a file. Again, the SaveFileDialog can be used as a control or a class. Once you have mas- tered the SaveFileDialog as a control, you will not have any problems using SaveFileDialog as a class. After you open a file, you may need to make some modifications to it and then save it. The SaveFileDialog control provides the same functionality as the OpenFileDialog control, except in reverse. It allows you to choose the location and filename as you save a file. It is important to note that the SaveFileDialog control does not actually save your file; it merely provides a dialog box to allow the user to locate where the file should be saved and to provide a name for the file. The Properties of SaveFileDialog The following table lists some of the properties that are available in the SaveFileDialog control. As you can see, this control, or class if you will, contains a wealth of properties that can be used to customize how the dialog box will behave. Property Description AddExtension Indicates whether an extension is automatically added to a filename if the user omits the extension. CheckFileExists Indicates whether the dialog box displays a warning if the user specifies a file name that does not exist. This is useful when you want the user to save a file to an existing name. CheckPathExists Indicates whether the dialog box displays a warning if the user specifies a path that does not exist. CreatePrompt Indicates whether the dialog box prompts the user for permission to cre- ate a file if the user specifies a file that does not exist. 220 Chapter 7 10_574019 ch07.qxd 9/16/05 9:21 PM Page 220 Property Description DefaultExt Indicates the default file extension. DereferenceLinks Indicates whether the dialog box returns the location of the file refer- enced by the shortcut or whether it returns the location of the shortcut itself. FileName Indicates the filename of the selected file in the dialog box. This is a read- only property. FileNames Indicates the filenames of all selected files in the dialog box. This is a read-only property that is returned as a string array. Filter Indicates the current filename filter string, which determines the choices that appear in the Files of type combo box in the dialog box. FilterIndex Indicates the index of the filter currently selected in the dialog box. InitialDirectory Indicates the initial directory displayed in the dialog box. OverwritePrompt Indicates whether the dialog box displays a warning if the user specifies a filename that already exists. RestoreDirectory Indicates whether the dialog box restores the current directory before closing. ShowHelp Indicates whether the Help button is displayed in the dialog box. Title Indicates the title that is displayed in the title bar of the dialog box. ValidateNames Indicates whether the dialog box should accept only valid Win32 filenames. The Methods of SaveFileDialog The SaveFileDialog control exposes the same methods as the OpenFileDialog does. If you want to review these methods, go back to the section “The Methods of OpenFileDialog”. All the examples will use the ShowDialog method to show the Save File dialog. Using the SaveFileDialog Control To see how to include the SaveFileDialog control in our project, you begin with the Dialogs project from the last Try It Out as a starting point and build upon it. In this exercise, you want to save the contents of the text box to a file. You use the SaveFileDialog control to display a Save File dialog box that allows you to specify the loca- tion and name of the file. Then you write the contents of the text box on your form to the specified file, again using a built-in code snippet provided by Visual Studio 2005. 221 Displaying Dialog Boxes 10_574019 ch07.qxd 9/16/05 9:21 PM Page 221 Try It Out: Working with SaveFileDialog 1. Open the Dialogs project from the last Try It Out. 2. On the form, add another button from the Toolbox and set its properties as follows: ❑ Set Name to btnSave. ❑ Set Anchor to Top, Right. ❑ Set Location to 367, 38. ❑ Set Text to Save. 3. In the Toolbox, scroll down until you see the SaveFileDialog control and then drag and drop it onto your form. The control will be added to the bottom on the workspace in the IDE. 4. Double-click the Save button to bring up its Click event and add the highlighted code: Private Sub btnSave_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSave.Click ‘Set the Save dialog properties With SaveFileDialog1 .DefaultExt = “txt” .FileName = strFileName .Filter = “Text files (*.txt)|*.txt|All files (*.*)|*.*” .FilterIndex = 1 .OverwritePrompt = True .Title = “Demo Save File Dialog” End With ‘Show the Save dialog and if the user clicks the Save button, ‘save the file If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then End If End Sub 5. Right click in the blank space between the If and End If statements and choose Insert Snippet from the context menu. In the drop-down menu that appears, double-click File System - Processing Drives, Folders, and Files and then scroll down the new list and double- click Write New Text Files. Your code should now look like this and you’ll notice that the filename test.txt is highlight as well as the string constant “some text”, indicating that this code needs to be changed: If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then Try Dim filePath As String filePath = System.IO.Path.Combine( _ My.Computer.FileSystem.SpecialDirectories.MyDocuments, _ “test.txt”) My.Computer.FileSystem.WriteAllText(filePath, “some text”, True) Catch fileException As Exception Throw fileException End Try End If 222 Chapter 7 10_574019 ch07.qxd 9/16/05 9:21 PM Page 222 6. Modify the code in the Try block as follows: Try ‘Save the file name strFileName = SaveFileDialog1.FileName Dim filePath As String ‘Open or Create the file filePath = System.IO.Path.Combine( _ My.Computer.FileSystem.SpecialDirectories.MyDocuments, _ strFileName) ‘Replace the contents of the file My.Computer.FileSystem.WriteAllText(filePath, txtFile.Text, False) Catch fileException As Exception 7. At this point, you are ready to test this code so run your project. Start with a simple test by opening an existing text file. Type some text into the text box on the form and then click the Save button. The Save dialog box will be displayed. Notice that the FileName combo box already has a filename in it. This is the filename that was set in the strFileName variable when you declared it in the previous Try It Out. 8. Enter a new filename, but do not put a file extension on it. Then click the Save button and the file will be saved. To verify this, click the Open button on the form to invoke the Open File dia- log box. You will see your new file. 9. To test the OverwritePrompt property of the SaveFileDialog control, enter some more text in the text box on the form and then click the Save button. In the Save File dialog box, choose an exist- ing filename and then click the Save button. You will be prompted to confirm replacement of the existing file as shown in Figure 7-9. If you choose Yes, the dialog box will return a DialogResult of OK, and the code inside your If . . . End If statement will be executed. If you choose No, you will be returned to the Save File dialog box so that you can enter another filename. Figure 7-9 When the Open File or Save File dialog box is displayed, the context menu is fully functional and you can cut, copy, and paste files, as well as rename and delete them. There are other options in the context menu that vary depending on what software you have installed. For example, if you have WinZip installed, you will see the WinZip options on the context menu. How It Works Before displaying the Save File dialog box, you need to set some properties to customize the dialog box to your application. The first property you set is the DefaultExt property. This property automatically 223 Displaying Dialog Boxes 10_574019 ch07.qxd 9/16/05 9:21 PM Page 223 sets the file extension if one has not been specified. For example, if you specify a filename of NewFile with no extension, the dialog box will automatically add .txt to the filename when it returns, so that you end up with a filename of NewFile.txt. .DefaultExt = “txt” The FileName property is set to the same path and filename as was returned from the Open File dialog. This allows you to open a file, edit it, and then display the same filename when you show the Save File dialog box. Of course, you can override this filename in the application’s Save File dialog box. .FileName = strFileName The next two properties are the same as in the OpenFileDialog control. They set the file extension filters to be displayed in the Save as type: combo box and set the initial filter: .Filter = “Text files (*.txt)|*.txt|All files (*.*)|*.*” .FilterIndex = 1 The OverwritePrompt property accepts a Boolean value of True or False. When set to True, this prop- erty prompts you with a MessageBox dialog box if you choose an existing filename. If you select Yes, the Save File dialog box returns a DialogResult of OK; if you select No, you are returned to the Save File dialog box to choose another filename. When the OverwritePrompt property is set to False, the Save File dialog box does not prompt you to overwrite an existing file, and your code will overwrite it with- out asking for the user’s permission. .OverwritePrompt = True The Title property sets the caption in the title bar of the Save File dialog box: .Title = “Demo Save File Dialog” After you have the properties set, you want to show the dialog box. The ShowDialog method of the SaveFileDialog control also returns a DialogResult, so you can use the SaveFileDialog control in an If . . . End If statement to test the return value. If the user clicks the Save button in the Save File dialog box, the dialog box returns a DialogResult of OK. If the user clicks the Cancel button in the dialog box, the dialog box returns a DialogResult of Cancel. The following code tests for Windows.Forms.DialogResult.OK: If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then The first thing that you do here is save the path and filename chosen by the user in your strFileName variable. This is done in case the user has chosen a new filename in the dialog box: Try ‘Save the file name strFileName = SaveFileDialog1.FileName Then you modify the code snippet generated by Visual Studio 2005 by replacing the highlighted text with your variables. First you replace the text “test.txt” with your variable, strFileName. This line 224 Chapter 7 10_574019 ch07.qxd 9/16/05 9:21 PM Page 224 of code opens the file for output. Then you replace the text “some text” with the Text property of the text box on your form. This last line of code reads the contents of your text box and writes it to the file. The False parameter at the end of this line of code indicates whether text should be appended to the file. A value of False indicates that the contents of the file should be overwritten. Dim filePath As String ‘Open or Create the file filePath = System.IO.Path.Combine( _ My.Computer.FileSystem.SpecialDirectories.MyDocuments, _ strFileName) ‘Replace the contents of the file My.Computer.FileSystem.WriteAllText(filePath, txtFile.Text, False) The final bit of code in this If . . . End If block merely wraps up the Try . . . Catch block and the If . . . End If statement. Catch fileException As Exception End Try End If The FontDialog Control Sometimes you may need to write an application that allows the user to choose the font in which they want their data to be displayed. Or perhaps you may want to see all available fonts installed on a partic- ular system. This is where the FontDialog control comes in; it displays a list of all available fonts installed on your computer in a standard dialog that your users have become accustomed to. Like the OpenFileDialog and SaveFileDialog controls, the FontDialog class can be used as a control by dragging it onto a form, or as a class by declaring it in code. The FontDialog control is really easy to use; you just set some properties, show the dialog box, and then query the properties that you need. The Properties of FontDialog The following table lists some of its available properties. Property Description AllowScriptChange Indicates whether the user can change the character set specified in the Script drop-down box to display a character set other than the one currently displayed. Color Indicates the selected font color. Font Indicates the selected font. FontMustExist Indicates whether the dialog box specifies an error condition if the user attempts to enter a font or style that does not exist. 225 Displaying Dialog Boxes 10_574019 ch07.qxd 9/16/05 9:21 PM Page 225 Property Description MaxSize Indicates the maximum size (in points) a user can select. MinSize Indicates the minimum size (in points) a user can select. ShowApply Indicates whether the dialog box contains an Apply button. ShowColor Indicates whether the dialog box displays the color choice. ShowEffects Indicates whether the dialog box contains controls that allow the user to specify strikethrough, underline, and text color options. ShowHelp Indicates whether the dialog box displays a Help button. The Methods of FontDialog You will only be using one method (ShowDialog) of FontDialog in the forthcoming Try It Out. Other methods available include Reset, which allows you to reset all the properties to their default values. Using the FontDialog Control You can display the FontDialog control without setting any properties: FontDialog1.ShowDialog() The dialog box would then look like Figure 7-10. Figure 7-10 226 Chapter 7 10_574019 ch07.qxd 9/16/05 9:21 PM Page 226 Notice that the Font dialog box contains an Effects section that enables you to check the options for Strikeout and Underline. However, color selection of the font is not provided by default. If you want this, you must set the ShowColor property before calling the ShowDialog method on the dialog box: FontDialog1.ShowColor = True FontDialog1.ShowDialog() The ShowDialog method of this dialog box, like all of the ones that you have examined thus far, returns a DialogResult. This will be either DialogResult.OK or DialogResult.Cancel. Once the dialog box returns, you can query for the Font and Color properties to see what font and color the user has chosen. You can then apply these properties to a control on your form or store them to a variable for later use. Now that you know what the Font dialog looks like and how to call it, you can use it in a Try It Out. You need to use the program from the last two Try It Outs to open a file, and have the contents of the file read into the text box on the form. You then use the FontDialog control to display the Font dialog box, which allows you to select a font. Then you change the font in the text box to the font that you have chosen. Try It Out Working with FontDialog 1. Open the Dialogs project again. 2. On the form add another button from the Toolbox and set its properties according to the values shown in this list: ❑ Set Name to btnFont. ❑ Set Anchor to Top, Right. ❑ Set Location to 367, 68. ❑ Set Text to Font. 3. You now need to add the FontDialog control to your project, so locate this control in the Toolbox and drag and drop it onto the form in the workspace below the form or on the form itself; the control will be automatically placed in the workspace below the form. Accept all default proper- ties for this control. 4. You want to add code to the Click event of the Font button, so double-click it and add the fol- lowing highlighted code: Private Sub btnFont_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnFont.Click ‘Set the FontDialog control properties FontDialog1.ShowColor = True ‘Show the Font dialog If FontDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then ‘If the OK button was clicked set the font ‘in the text box on the form 227 Displaying Dialog Boxes 10_574019 ch07.qxd 9/16/05 9:21 PM Page 227 [...]... your Visual Basic 2005 applications You explore how to create and manage menus and submenus and how to create context menus and override the default context menus Visual Studio 2005 provides two menu controls in the Toolbox, and you will be exploring both of these In this chapter, you will: ❑ Create menus ❑ Create submenus ❑ Create context menus Understanding Menu Features The MenuStrip control in Visual. .. will incorporate some kind of printing capabilities, whether it is basic printing or more sophisticated printing, such as allowing a user to print only selected text or a range of pages In this next section of the chapter you explore basic printing You take a look at several classes that help you to print text from a file Visual Basic 2005 provides the PrintDialog control It does not actually do any... of the form itself, a control, or of text in a text box Visual Basic 2005 provides the ColorDialog control for all such requirements Once again, the ColorDialog control can also be used as a class — declared in code without dragging a control onto the Form Designer The ColorDialog control, shown in Figure 7-12, allows the user to choose from 48 basic colors Figure 7-12 Notice that the users can also... Folder dialog box, you needed to set some basic properties of the FolderBrowserDialog control to customize the look for this dialog box You started by setting the Description property to provide some basic instructions for your user Then you selected the root folder at which the Browse For Folder dialog box should start browsing In this instance, you used the 244 Displaying Dialog Boxes MyComputer constant,... Chapter 8 Images Everyone has seen images on the menus in their applications, such as Microsoft Word and even Visual Studio 2005 itself Up until now, developers were unable to create menu items with images without some custom programming or purchasing a third-party control Visual Studio 2005 now provides an Image property for a menu item that makes adding an image to your menu items a breeze Access... as shown in Figure 8-5 You can also click the other menus and see their menu items Figure 8-5 How It Works Visual Studio 2005 takes care of a lot of the details for you by providing the Insert Standard Items context menu item in the MenuStrip control By clicking this menu item, Visual Studio 2005 created the standard menus and menu items found in most common applications This allows you to concentrate... button next to the Image property In the Select Resource dialog box, click the Import button and browse to C:\Program Files\ Microsoft Visual Studio 8\Common7\VS2005ImageLibrary\bitmaps\commands\high color folder This path assumes a default installation of Visual Studio 2005 In the Open dialog box, select AlignTableCellMiddleLeftJustHS.bmp and then click the Open button Next, click the OK button in the... another submenu within a submenu 249 Chapter 8 Keep in mind, though, that if the menus are hard to navigate, or if it is hard to find the items your users are looking for, the users will rapidly lose faith in your application You should stick with the standard format for menus that you see in most Windows applications today These are the menus that you see in Visual Studio 2005, Microsoft Word, or Microsoft... SelectedPath property: ‘Display the selected folder txtFile.Text = FolderBrowserDialog1.SelectedPath End If Summar y This chapter has taken a look at some of the dialog boxes that are provided in Visual Basic 2005 You examined the MessageBox dialog box, and the OpenFileDialog, SaveFileDialog, FontDialog, ColorDialog, PrintDialog, and FolderBrowserDialog controls Each of these dialog boxes will help you... FolderBrowserDialog class (not the control) and display the selected folder in the label on your form 246 8 Creating Menus Menus are a part of every good application and provide not only an easy way to navigate within an application but also useful tools for working with that application Take, for example, Visual Studio 2005 It provides menus for navigating the various windows that it displays and useful tools . generated by Visual Studio 2005 by replacing the highlighted text with your variables. First you replace the text “test.txt” with your variable, strFileName. This line 2 24 Chapter 7 10_5 740 19 ch07.qxd. the specified file, again using a built-in code snippet provided by Visual Studio 2005. 221 Displaying Dialog Boxes 10_5 740 19 ch07.qxd 9/16/05 9:21 PM Page 221 Try It Out: Working with SaveFileDialog 1. Open. their form. This may be the color of the form itself, a control, or of text in a text box. Visual Basic 2005 provides the ColorDialog control for all such requirements. Once again, the ColorDialog

Ngày đăng: 12/08/2014, 10:21

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

Tài liệu liên quan