YOMEDIA
ADSENSE
Professional VB 2005 - 2006 phần 6
72
lượt xem 8
download
lượt xem 8
download
Download
Vui lòng tải xuống để xem tài liệu đầy đủ
Đặt một nút ở góc dưới bên phải của biểu mẫu, và thiết lập thuộc tính Neo cho các nút hại và phải. Sau đó, đặt hai hộp văn bản trong FlowLayoutPanel, giữ kích thước mặc định của họ. Các hình thức mà bạn đã tạo ra nên bây giờ trông giống như hình 14-14.
AMBIENT/
Chủ đề:
Bình luận(0) Đăng nhập để gửi bình luận!
Nội dung Text: Professional VB 2005 - 2006 phần 6
- Chapter 14 Place a button in the bottom-right corner of the form, and set the Anchor property for the button to Bottom and Right. Then place two text boxes in the FlowLayoutPanel, keeping their default sizes. The form you have created should now look much like that in Figure 14-14. impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 14-14 Now run the application. The initial layout will be similar to the design-time layout. However, if you resize the form to about half of its original width, the layout of the text boxes will change. Since there is no longer enough room for them to be arranged side by side, the arrangement will automatically switch, and the form will look more like that in Figure 14-15. Figure 14-15 Padding and Margin properties To assist in positioning controls in the FlowLayoutPanel, all controls have a new property called Margin. There are settings for Margin.Left, Margin.Right, Margin.Top, and Margin.Bottom. These settings determine how much space is reserved around a control when calculating its automatic position in a FlowLayoutPanel. You can see the Margin property in action by changing the Margin property for one or more of the text boxes in the previous example. If you change all the Margin settings for the first Textbox to 20 pixels, for example, and run the application, the form will look like Figure 14-16. 518
- Windows Forms impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 14-16 The first text box now has a 20 pixel separation from all the other controls in the FlowLayoutPanel, as well as a 20 pixel separation from the edges of the FlowLayoutPanel itself. The Padding property is for the FlowLayoutPanel or other container control. When a control is embedded into a FlowLayoutPanel, the Padding.Left, Padding.Right, Padding.Top, and Padding.Bottom properties of the FlowLayoutPanel determine how far away from the inside edge of the container to position the control. You can see the Padding property in action by changing the Padding property for the FlowLayoutPanel in the previous example. If you set all Padding settings to 20 pixels, and reset the Margin property for the first Textbox back to the default, then the form will look like Figure 14-17 in the visual designer. Figure 14-17 519
- Chapter 14 Notice that all the controls in the FlowLayoutPanel are now at least 20 pixels from the edges. The Padding property is also applicable for other container controls, if the contained controls have their impo PDF Merge andIfSplit Unregistered Version - http://www.simpopdf.com the edge Dock property set. the settings for Padding are not zero, a docked control will be offset from of the container by the amount specified by the Padding property. TableLayoutPanel Control The other new control for dynamic layout is the TableLayoutPanel. This control consists of a table of rows and columns, resulting in a rectangular array of cells. You can place one control in each cell. The dimensions of the columns and rows can be controlled by setting some key properties. For columns, set the number of columns with the ColumnCount property, and then control each individual column with the ColumnStyles collection. When you click on the button for the ColumnStyles collection, you’ll get a designer window that allows you to set two key properties for each column — the SizeType and Width properties. SizeType can be set to one of the following enumerations: ❑ Absolute — Sets the column width to a fixed size in pixels ❑ AutoSize — Indicates that the size of the column should be managed by the TableLayoutPanel, which will allocate width to the column depending on the widest control contained in the column ❑ Percent — Sets the percentage of the TableLayoutPanel to use for the width of the column The Width property is only applicable if you do not choose a SizeType of AutoSize. It sets either the number of pixels for the width of the column (if the SizeType is Absolute) or the percentage width for the column (if the SizeType is set to Percent). Similarly, for rows, there is a RowCount property to set the number of rows, and a RowStyles collection to manage the size of the rows. Each row in RowStyles has a SizeType, which works the same way as SizeType does for Columns, except that it manages the height of the row instead of the width of a col- umn. The Height property is used for rows instead of a Width property, but it works in a corresponding way. Height is either the number of pixels (if SizeType is Absolute) or a percentage of the height of the TableLayoutPanel (if SizeType is Percent). If SizeType is AutoSize, then a row is sized to the height of the tallest control in the row. Extender Provider Controls There is a new family of controls in Windows Forms that can only be used in association with other controls. Each of these controls, called extender provider controls, causes new properties to appear for every other control on the form. Extender provider controls have no visible manifestation, so they appear in the component tray. The three extender provider controls currently available are the HelpProvider, the ToolTip, and the ErrorProvider. All three controls work in basically the same way. Each extender provider control 520
- Windows Forms implements the properties that are “attached” to other controls. The best way to see how this works is to go through an example, so let’s do that with a ToolTip control. impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ToolTip The ToolTip control is the simplest of the extender providers. It adds just one property to each control, named ToolTip on ToolTip1 (assuming the ToolTip control has the default name of ToolTip1). This property works exactly the same way the ToolTipText property works in VB6, and in fact, replaces it. To see this in action, create a Windows Forms application. On the blank Form1 that is created for the project, place a couple of buttons. Take a look at the properties window for Button1. Notice that it does not have a ToolTip property of any kind. Drag over the ToolTip control, which will be placed in the component tray. Go back to the properties window for Button1. A property named ToolTip on ToolTip1 is now present. Set any string value you like for this property. Now run the project, and hover the mouse pointer over Button1. You will see a tooltip containing the string value you entered for the ToolTip on ToolTip1 property. HelpProvider The HelpProvider control allows controls to have associated context-sensitive help available by pressing F1. When a HelpProvider control (named HelpProvider1 by default) is added to a form, all controls on the form get these new properties, which show up in the controls’ Properties window. Property Usage Provides a pop-up tooltip for the control when shape HelpString on HelpProvider1 F1 is pressed while the control has the focus. If the HelpKeyword and HelpNavigator properties (see later) are set to provide a valid reference to a help file, then the HelpString value is ignored in favor of the information in the help file. Provides a keyword or other index to use in a help HelpKeyword on file for context-sensitive help for this control. The HelpProvider1 HelpProvider1 control has a property that indicates the help file to use. This replaces the HelpContextID property in VB6. Contains an enumerated value that determines how the HelpNavigator on value in HelpKeyword is used to refer to the help file. HelpProvider1 There are several possible values for displaying such elements as a topic, an index, or a table of contents in the help file. Determines whether the HelpProvider control is active ShowHelp on for this control. HelpProvider1 521
- Chapter 14 Filling in the HelpString property immediately causes the control to provide tooltip help when F1 is pressed while the control has the focus. The HelpProvider control has a property to point to a help file (either an HTML help file or a Win32 help file), and the help topic in the HelpTopic property points to a topic in this file. impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ErrorProvider The ErrorProvider control presents a simple, visual way to indicate to a user that a control on a form has an error associated with it. The added property for controls on the form when an ErrorProvider control is used is called Error on ErrorProvider1 (assuming the ErrorProvider has the default name of ErrorProvider1). Setting this property to a string value causes the error icon to appear next to a control, and for the text to appear in a tooltip if the mouse hovers over the error icon. Here is a screen with several text boxes, and an error icon next to one (with a tooltip). The error icon and tooltip are displayed and managed by the ErrorProvider control, as shown in Figure 14-18. The ErrorProvider control’s default icon is the red circle with an exclamation point. When the Error property for the text box is set, the icon will blink for a few moments, and hovering over the icon will cause the tooltip to appear. The code for this behavior in the example screen is explained in the next topic. Figure 14-18 Properties of Extender Providers In addition to providing other controls with properties, extender provider controls also have properties of their own. For example, the ErrorProvider control has a property named BlinkStyle. When it is set to NeverBlink, the blinking of the icon is stopped for all controls that are affected by the ErrorProvider. 522
- Windows Forms Other properties of the ErrorProvider allow you to change things such as the icon used, and where the icon will appear in relation to the field that has the error. For instance, you might want the icon to show up beneath a field, instead. You can also have multiple error providers on your form. For example, Merge and Split to give the user a warning rather than an error. A second error provider with a yellow you may wish Unregistered Version - http://www.simpopdf.com impo PDF icon could be used to provide this feature. Working with Extender Provider Controls in Code Setting the Error property in the previous example can be done with the Property window, but this is not very useful for on-the-fly error management. However, setting the Error property in code is not done with typical property syntax. By convention, extender provider controls have a method for each property they need to set, and the arguments for the method include the associated control and the property setting. To set the Error property in the previous example, the following code was used: ErrorProvider1.SetError(txtName, “You must provide a location!”) The name of the method to set a property is the word Set prefixed to the name of the property. This line of code shows that the Error property is set with the SetError (), method of the ErrorProvider. There is a corresponding method to get the value of the property, and it is named with Get prefixed to the name of the property. To find out what the current Error property setting for txtName is, you would use the following line: sError = ErrorProvider1.GetError(txtName) Similar syntax is used to manipulate any of the properties managed by an extender provider control. The discussion of the tooltip provider earlier talked about setting the tooltip property in the Properties window. To set that same property in code, the syntax would be ToolTip1.SetToolTip(Button1, “New tooltip for Button1”) Advanced Capabilities for Data Entry New for Windows Forms 2.0 are a couple of advanced capabilities for data entry. Textbox and Combobox controls now have autocompletion capabilities, and a new MaskedTextbox allows entry of formatted input such as phone numbers. Autocompletion Responsive user interfaces help users accomplish their purposes, thereby making them more productive. One classic way to do this is with autocompletion. An example of autocompletion is IntelliSense in Visual Studio. Using IntelliSense, the user only has to type in a few letters, and Visual Studio presents a list of probable entries matching those letters. If what the user wants is in the list, the user need only indicate that, rather than typing the entire entry. 523
- Chapter 14 Autocompletion is available in Windows Forms 2.0 with text boxes and combo boxes. Both use a set of properties to control how autocompletion works and where the list of entries available to the user comes from. impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com To see autocompletion in action, create a Windows Application project. Drag a text box from the toolbox onto the blank Form1 created for the project. Set the AutocompleteMode for the text box to Suggest in the Property window. Then set the AutocompleteSource to CustomSource. Finally, click the button in the setting window for AutoCompleteCustomSource. You’ll see a window for entering entries that is very similar to the window for entering items for a list box or combo box. Enter the following items into the dialog: Holder Holland Hollis Holloway Holly Holstein Holt Now, start the project, and type “Hol” into the text box. As soon as you start typing, a drop-down will appear that contains entries matching what you’ve typed, which includes all seven elements in the list. If you then type another 1, the list will decrease to four elements that begin with Holl. (See Figure 14-19.) If you then type an o, the list will contain only the entry Holloway. The AutoCompleteMode has two other modes. The Append mode does not automatically present a drop-down, but instead appends the rest of the closest matching entry to the text in the Textbox or ComboBox, and highlights the untyped characters. This allows the closest matching entry to be placed in the textarea without the user explicitly selecting an entry. The SuggestAppend mode combines Suggest and Append. The current best match is displayed in the textarea, and the drop-down with other possibilities is automatically displayed. This mode is the one most like IntelliSense. You can also set the list of items to be included in the autocompletion list at runtime, and this would be the most common usage scenario. A list of items from a database table would typically be loaded for autocompletion. MaskedTextbox Control The new features summary discussed the addition of a MaskedTextbox control, which fills in for the old VB6 MaskedEdit control. If you have used MaskedEdit in VB6, the MaskedTextbox will feel quite familiar. After dragging a MaskedTextbox control to a form, you will typically want to first set the mask associated with the control. You can do this in the property window by selecting the Mask property, but you can also click the right-pointing arrow on the right side of the MaskedTextbox. In either case, you can either construct a mask manually or select one of the commonly used masks from a list. 524
- Windows Forms If you need to create your own mask, you will need to design it based on a set of formatting characters: impo PDF Merge Mask Split Unregistered Version - http://www.simpopdf.com and Character Description Digit placeholder. # Decimal placeholder. The actual character used is the one . specified as the decimal placeholder in your international settings. This character is treated as a literal for masking purposes. Thousands separator. The actual character used is the one , specified as the thousands separator in your international settings. This character is treated as a literal for masking purposes. Time separator. The actual character used is the : one specified as the time separator in your international settings. This character is treated as a literal for masking purposes. Date separator. The actual character used is the one / specified as the date separator in your international settings. This character is treated as a literal for masking purposes. Treat the next character in the mask string as a literal. \ This allows you to include the #, &, A, and ? characters in the mask. This character is treated as a literal for masking purposes. Character placeholder. Valid values for this placeholder are & ANSI characters in the following ranges: 32–126 and 128–255. Convert all the characters that follow to uppercase. > Convert all the characters that follow to lowercase. < Alphanumeric character placeholder (entry required). For A example: a–z, A–Z, or 0–9. Alphanumeric character placeholder (entry optional). a Digit placeholder (entry optional). For example: 0–9. 9 Character or space placeholder (entry optional). This operates C exactly like the & placeholder, and ensures compatibility with Microsoft Access. Letter placeholder. For example: a–z or A–Z. ? Literal All other symbols are displayed as literals; that is, as themselves. 525
- Chapter 14 Literal characters are simply inserted automatically by the MaskedTextbox control. If you have literal characters for the parentheses in a phone number, for example, the user need not type these for them to show up in the textarea of the control. impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com As an example of a mask, suppose that you have an account number that must consist of exactly two uppercase letters and five digits. You could construct a mask of >??00000. The first character forces all letters to uppercase. The two question marks specify two required alphabetic characters, and the five zeros specify five required digits. Once you have set the Mask for the MaskedTextbox, all entries into the control will be coerced to the Mask pattern. Keystrokes that don’t fit will be thrown away. You have two options for fetching the text information entered by the user in a MaskedTextbox. The InputText property will get the entry without any of the literal placeholder characters. For example, if you are using a mask for phone number, InputText will just return the ten digits in the phone number. If you want the text exactly as it appears in the control, then you should use the normal Text property. Validating Data Entry Most controls that you place on a form require that their content be validated in some way. A text box might require a numeric value only or simply require that the user provide any value and not leave it blank. The ErrorProvider control just covered makes this task significantly easier than it was in previous versions. To illustrate the use of this control in data validation, create a new Windows application project and change the Text property for the blank Form1 to Validating Demo. Then place two text boxes on the form that will hold a username and password, as shown in Figure 14-19. Figure 14-19 526
- Windows Forms Name the first text box UserNameTextBox and the second text box PasswordTextBox. You also need to drag an ErrorProvider control onto the form, which will cause it to appear in the Component Tray. In the next section, you’ll add the code that will simply verify that the user has filled in both text boxes and Merge andvisual indication, via the ErrorProvider, if either of the fields has been left blank. given a Split Unregistered Version - http://www.simpopdf.com impo PDF The Validating Event The Validating event fires when your control begins its validation. It is here that you need to place your code that will validate your control, and set a visual indication for the error. Insert the following code to see this in action: Private Sub UserNameTextBox_Validating(ByVal sender As Object, _ ByVal e As System.ComponentModel.CancelEventArgs) _ Handles UserNameTextBox.Validating If userNameTextbox.Text = “” Then ErrorProvider1.SetError(UserNameTextBox, “User Name cannot be blank”) Else ErrorProvider1.SetError(UserNameTextBox, “”) End If End Sub Private Sub PasswordTextBox_Validating(ByVal sender As Object, _ ByVal e As System.ComponentModel.CancelEventArgs) _ Handles PasswordTextBox.Validating If passwordTextbox.Text = “” Then ErrorProvider1.SetError(PasswordTextBox, “Password cannot be blank”) Else ErrorProvider1.SetError(PasswordTextBox, “”) End If End Sub Run the program and the tab between the controls without entering any text to get the error message. You’ll see an icon blink next to each of the text box controls, and if you hover over an error icon, you’ll see the appropriate error message. There is also a Validated event that fires after a control’s Validating event. It can be used, for example, to do a final check after other events have manipulated the contents of the control. The CausesValidation Property The CausesValidation property determines if the control will participate in the validation events on the form. A control with a CausesValidation setting of True (it is True by default) will have two effects: ❑ The control’s Validating/Validated events will fire when appropriate. ❑ The control will trigger the Validating/Validated events for other controls. It is important to understand that the validation events fire for a control not when the focus is lost but when the focus shifts to a control that has a CausesValidation value of True. 527
- Chapter 14 To see this effect, set the CausesValidation property of the password text box in your application to False (be sure to leave it True for the username and OK button). When you run the program, tab off the username text box and again to the OK button. Notice that it isn’t until the focus reaches the OK PDF Merge and Split event of the username text box fires. Also, notice that the validating event of button that the validating Unregistered Version - http://www.simpopdf.com impo the password field never fires. Ultimately, if you determine that the control is not valid, you need to decide how to act. That may include setting the focus to the control that needs attention (as well as indicating the error with an ErrorProvider). Toolbars and the New ToolStrip Control As mentioned in the summary of new features in Windows Forms 2.0, the ToolStrip control replaces the Toolbar control from Windows Forms 1.0 and 1.1. ToolStrip has many improvements. It supports movement to other sides of a form than the place it was laid out, and you have much more flexibility in placing items on the toolbar. It also integrates better with the IDE to assist in creating toolbars and manipulating the many settings available. The ToolStrip does not sit alone on a form. When a ToolStrip is dragged onto a form, the container that actually sits on the form is called a RaftingContainer. This container handles the positioning, so that the toolbar created by a ToolStrip can be dragged to other parts of the form. The ToolStrip sits inside the RaftingContainer and is the container for toolbar elements. It handles the sizing of the toolbar, movement of toolbar elements, and other general toolbar functions. The items on the toolbar must be from a set of controls specially designed to serve as toolbar items. All of these items inherit from the ToolStripItem base class. The controls available for toolbar items are: Control Description Replicates the functionality of a regular Button for a toolbar ToolStripButton Replicates the functionality of a regular Label for a toolbar ToolStripLabel A visual toolbar element that displays a vertical bar to ToolStripSeparator separate other groups of elements (no user interaction) Replicates the functionality of a regular ComboBox for a ToolStripComboBox toolbar. This item must be contained within a ToolStrip- ControlHost (see below). Replicates the functionality of a regular TextBox for a ToolStripTextBox toolbar. This item must be contained within a ToolStrip- ControlHost (see below) A hosting container for other controls that reside on a ToolStripControlHost ToolStrip. It can host any of the following controls: ToolStripComboBox, ToolStripTextBox, other Windows Forms controls, or user controls. 528
- Windows Forms Control Description A hosting container for toolbar elements that feature drop- ToolStripDropDownItem impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com down functionality. Can host a ToolStripMenuItem, a ToolStripSplitButton, or a ToolStripDropDownButton. A button that supports drop-down functionality. Clicking ToolStripDropDownButton the button shows a list of options, and the user must then click the one desired. This item is used when the user needs to select from a group of options, no one of which is used a large majority of the time. A combination of a regular button and a drop-down button. ToolStripSplitButton This item is often used when there is a frequently used option to click, but you also need to offer the user other options that are less frequently used. A selectable option displayed on a menu or context menu. ToolStripMenuItem This item is typically used with the menu controls that inherit from the ToolStrip, and which are discussed in the section later in this chapter entitled “Menus.” Notice that almost any control can be hosted on a toolbar using the ToolStripControlHost. However, for buttons, text boxes, labels, and combo boxes, it is much easier to use the ToolStrip version instead of the standard version. Creating a ToolStrip and Adding Toolbar Elements Let’s do an example to see how to build a toolbar using the ToolStrip control. Create a new Windows application. Add a ToolStrip control to the blank Form1 that is included with the new project. Make the form about twice its default width, so that you have plenty of room to see the ToolStrip as you work on it. The ToolStrip will be positioned at the top of the form by default. It will not contain any elements, though if you highlight the ToolStrip control in the component tray, a “menu designer” will appear in the ToolStrip. The easiest way to add multiple elements to the ToolStrip is to use the designer dialog for the ToolStrip. Highlight the ToolStrip in the component tray and click the button in the properties window for the Items property. You’ll see a designer dialog that looks like Figure 14-20. 529
- Chapter 14 impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 14-20 The drop-down in the upper left contains the different types of items that can be placed on the toolbar. Add one each of the following types, with the setting specified: Set the Text property to Go. ToolStripButton Set the Text property to blank. ToolStripComboBox Set DropDownStyle to DropDownList. Open the Items dialog and add the names of some colors. Set the Text property to Options. ToolStripSplitButton Set the Text property to blank. ToolStripTextBox Then click OK in the dialog, and the ToolStrip will look like the one in Figure 14-21. Figure 14-21 You can now handle events on any of these toolbar elements the same way you would any other controls. You can double-click to get a Click event routine or access the event routines through the drop-downs in the Code Editor. Run your program and, using the mouse, grab the dotted handle on the far-left edge of the toolbar. If you drag this to the right, the toolbar will be repositioned. If you drag it to other positions on the form, the entire toolbar will dock to different edges of the form. 530
- Windows Forms Allowing the User to Move Toolbar Elements By default, the AllowReorder property of the ToolStrip is set to False. If you change that to True, then the elements on the toolbar can be moved around in relation to one another at runtime (reordered). impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Change the AllowReorder property to True for the ToolStrip, and run your program again. Hold down the Alt key, and drag elements on the toolbar around. They will assume new positions on the toolbar when you drop them. Creating a Standard Set of Toolbar Elements If you need a toolbar that has the typical visual elements for cut, copy, paste, and so on, it is not necessary for you to create the elements. The designer will do it for you. Create a new form in your project, and drag a ToolStrip onto the form. As before, it will be positioned at the top and will not contain any elements. With the ToolStrip highlighted in the component tray, click the Item property. Below the properties in the Property window, a link named Insert Standard Items will appear. Click that link, and elements will be inserted into the ToolStrip to make it look like the one in Figure 14-22. Figure 14-22 Altering Toolbar Elements in the Designer When a ToolStrip or element with a ToolStrip is highlighted in the Visual Designer, a small right-pointing arrow is displayed on the right-hand side of the element. If you click this arrow, you will see a dialog that allows you to change the most commonly used properties of the element. This is just a convenience feature — the properties window can also be used to change these properties, along with any other properties of the element. Menus Menus are added to a form in VB.NET 2005 by dragging controls called MenuStrip or ContextMenuStrip onto your form. MenuStrip implements a standard Windows-style menu at the top of the form. ContextMenuStrip allows a pop-up menu with a right mouse button click. These controls are actually subclasses of the ToolStrip, so much of the information you learned earlier in this chapter for working with the ToolStrip also applies to the MenuStrip and ContextMenuStrip. 531
- Chapter 14 When dragged onto the form, these controls appear in the component tray just as the ToolStrip does, and you access the designer for these controls the same way as you do for the ToolStrip. However, because these are menus, the most common way of adding items is to type items directly into the menu PDF Merge appears when the control is highlighted. - http://www.simpopdf.com designer that and Split Unregistered Version impo The menu designer is extremely intuitive — the menu appears on your form just as it would at runtime, and you simply fill in the menu items you need. Each item can be renamed, and each can have a Click event associated with it. Adding Standard Items to a Menu If your form’s menu needs to have the standard top-level options (File, Edit, and so on) and the typical options under these items, then you can have all these typical options inserted for you automatically. To see this capability in action, drag a MenuStrip to a form, and then click the right arrow at the right edge of the MenuStrip to bring up the designer dialog. Click the link at the bottom of the dialog that says Insert Standard Items. Icons and Checkmarks for Menu Items Each item on a menu has an Image property. Setting this property to an image causes the image to appear on the left side of the text for the menu option. You can see this property in use by looking at the standard items inserted in the example just above. The File ➪ Save option has an icon of a diskette, which was produced by setting the image property of that item. Items can also have checkmarks beside them. This is done by changing the Checked property of the item to True. This can be done at design time or runtime, allowing you to manipulate the checkmarks on menus as necessary. Context Menus To implement a context menu for a form or any control on a form, drag a ContextMenuStrip to the form, and add the menu items. Items are added and changed the same way as with the MenuStrip. To hook a context menu to a control, set the control’s ContextMenuStrip property to the ContextMenuStrip menu control you want to use. Then, when your program runs and you right-click in the control, the context menu will pop up. Dynamically Manipulating Menus at Runtime Menus can be adjusted at runtime using code. Context menus, for instance, may need to change depending on the state of your form. The following walkthrough shows how to add a new menu item to a context menu and also how to clear the menu items. First, create a new Windows application. On the blank Form1 for the project, drag over a MenuStrip control. Using the menu designer, type in a top-level menu option of File. Under that option, type in options for Open and Save. Now place a button on the form. Double-click the button to get its Click event, and place the following code into the event: 532
- Windows Forms Dim NewItem As New ToolStripMenuItem NewItem.Text = “Save As” ‘ Set any other properties of the menu item you like. impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com FileToolStripMenuItem.DropDownItems.Add(NewItem) AddHandler NewItem.Click, _ AddressOf Me.NewMenuItem_Click Then add the event handler referenced in this code at the bottom of the form’s code: Private Sub NewMenuItem_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) MessageBox.Show(“New menu item clicked!”) End Sub If you now run the program and look at the menu, it will only have File and Save options. Clicking the button will cause a new Save As item to be added to the menu, and it will be hooked to the event routine called NewMenuItem_Click. Common Dialogs VB.NET provides you with seven common dialog controls. Each is a control that will open a predefined form that is identical to the one used by the operating system. The next sections outline the use and basic properties of each control that customizes their use. OpenFileDialog and SaveFileDialog These two controls will open the standard dialog control that allows a user to select files on the system. They are virtually identical, except for the buttons and labels that appear on the actual dialog box when it is shown to the user. Each prompts the user for a file on the system, by allowing the user to browse the files and folders available. Use the following properties to set up the dialog boxes. Property Comments Defines the initial location that will be displayed when the InitialDirectory dialog box opens. For example: OpenFileDialog1 .InitialDirectory = “C:\Program Files” String that defines the Files of type list. Separate items using Filter the pipe character. Items are entered in pairs with the first of each pair being the description of the file type, and the second half as the file wildcard. For example: OpenFileDialog1.Filter = “All Files$|*.* |Text Files|*.txt|Rich Text Files|*.rtf” Table continued on following page 533
- Chapter 14 Property Comments Integer that specifies the default filter item to use when the FilterIndex impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com dialog box opens. For example, with the above filter used, default to text files as follows: OpenFileDialog1.FilterIndex = 2 Boolean value that, if True, will force the system’s default RestoreDirectory directory to be restored to the location it was in when the dialog box was first opened. This is False by default. Holds the full name of the file that the user selected, Filename including the path. Displays the dialog. ShowDialog() The following code will open the standard dialog box asking the user to select a file that currently exists on the system, and will simply display the choice in a message box upon return: OpenFileDialog1.InitialDirectory = “C:\” OpenFileDialog1.Filter = “Text files|*.txt|All files|*.*” OpenFileDialog1.FilterIndex = 1 OpenFileDialog1.RestoreDirectory = True OpenFileDialog1.ShowDialog() MessageBox.Show(“You selected “”” & OpenFileDialog1.FileName & “”””) ColorDialog Control As the name implies, this control gives the user a dialog box from which to select a color. Use the following properties to set up the dialogs boxes. Using these properties looks something like this: ColorDialog1.Color = TextBox1.BackColor ColorDialog1.AllowFullOpen = True ColorDialog1.ShowDialog() TextBox1.BackColor = ColorDialog1.Color Property Comments The System.Drawing.Color that the user selected. You Color can also use this to set the initial color selected when the user opens the dialog. Boolean value that, if True, will allow the user to select any AllowFullOpen color. If False, the user is restricted to the set of default colors. Displays the dialog. ShowDialog() 534
- Windows Forms FontDialog Control This control will display the standard dialog box, allowing a user to select a font. Use the following properties to set up the dialog boxes. impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Property Comments The System.Drawing.Font that the user selected. Also Font used to set the initial font. Boolean value that, if True, will make the dialog box ShowEffects display the text effects options of underline and strikeout. Boolean value that, if True, will make the dialog box ShowColor display the combo box of the font colors. The ShowEffects property must be True for this to have an effect. Boolean value that, if True, will limit the list of font choices FixedPitchOnly to only those that have a fixed pitch (such as Courier, or Lucida console). Displays the dialog. ShowDialog() Using these properties looks like this: FontDialog1.Font = TextBox1.Font FontDialog1.ShowColor = True FontDialog1.ShowEffects = True FontDialog1.FixedPitchOnly = False FontDialog1.ShowDialog() TextBox1.Font = FontDialog1.Font Printer Dialog Controls There are three more common dialog controls: PrintDialog, PrintPreviewDialog, and PageSetupDialog. They can all be used to control the output of a file to the printer. You can use these in conjunction with the PrintDocument component to run and control print jobs. Drag and Drop Implementing a drag-and-drop operation in the .NET Framework is accomplished by a short sequence of events. Typically, it begins in a MouseDown event of one control, and always ends with the DragDrop event of another. To demonstrate the process, you’ll begin with a new Windows Application. Add two list boxes to your form, and add three items to the first using the Items Property Designer. This application will allow you to drag the items from one list box into the other. 535
- Chapter 14 The first step in making drag and drop work is specifying whether or not a control will accept a drop. By default, all controls will reject such an act and not respond to any attempt by the user to drop something onto them. In your case, set the AllowDrop property of the second list box (the one without the items added) to True. impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The next item of business is to invoke the drag-and-drop operation. This is typically done in the MouseDown event of the control containing the data you want to drag (although you’re not restricted to it). The DoDragDrop method is used to start the operation. This method defines the data that will be dragged, and the type of dragging that will be allowed. In the present situation, you’ll drag the text of the selected list box item, and you’ll permit both a move and a copy of the data to occur. Switch over to the code window of your form and add the following code to the MouseDown event of ListBox1: Private Sub ListBox1_MouseDown(ByVal sender As Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _} Handles ListBox1.MouseDown Dim DragDropResult As DragDropEffects If e.Button = MouseButtons.Left Then DragDropResult = ListBox1.DoDragDrop( _ ListBox1.Items(ListBox1.SelectedIndex), _ DragDropEffects.Move Or DragDropEffects.Copy) ‘ Leave some room here to check the result of the operation ‘ (You’ll fill it in next). End If End Sub You’ll notice the comment here about leaving room to check the result of the operation. You’ll fill that in shortly. For now, calling the DoDragDrop method has got you started. The next step involves the recipient of the data, in your case, ListBox2. There are two events here that will be important to monitor — the DragEnter and DragDrop events. As can be predicted by the name, the DragEnter event will occur when the user first moves over the recipient control. The DragEnter event has a parameter of type DragEventArgs that contains an Effect property and a KeyState property. The Effect property allows you to set the display of the drop icon for the user to indicate if a move or a copy will occur when the mouse button is released. The KeyState property allows you to determine the state of the Ctrl, Alt, and Shift keys. It is a Windows standard that when both a move or a copy can occur, a user is to indicate the copy action by holding down the Ctrl key. Therefore, in this event, you will check the KeyState property and use it to determine how to set the Effect property. Add the following code to the DragEnter event of ListBox2: 536
- Windows Forms Private Sub ListBox2_DragEnter(ByVal sender As Object, _ ByVal e As DragEventArgs) _ Handles ListBox2.DragOver impo PDF Merge andIf e.KeyState = 9 ThenVersion - http://www.simpopdf.com Split Unregistered ‘ Control key e.Effect = DragDropEffects.Copy Else e.Effect = DragDropEffects.Move End If End Sub Note that you can also use the DragOver event if you want, but it will fire continuously as the mouse moves over the target control. In this situation, you only need to trap the initial entry of the mouse into the control. The final step in the operation occurs when the user lets go of the mouse button to drop the data at its destination. This is captured by the DragDrop event. The parameter contains a property holding the data that is being dragged. It’s now a simple process of placing it into the recipient control as follows: Private Sub ListBox2_DragDrop(ByVal sender As Object, _ ByVal e As System.Windows.Forms.DragEventArgs) _ Handles ListBox2.DragDrop ListBox2.Items.Add(e.Data.GetData(DataFormats.Text)) End Sub One last step — you can’t forget to manipulate ListBox1 if the drag and drop was a move. Here’s where you’ll fill in the hole you left in the MouseDown event of ListBox1. Once the DragDrop has occurred, the initial call that invoked the procedure will return a result indicating what ultimately happened. Go back to the ListBox1_MouseDown event and enhance it to remove the item from Listbox1 if it was moved (and not simply copied): Private Sub ListBox1_MouseDown(ByVal sender As Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles ListBox1.MouseDown Dim DragDropResult As DragDropEffects If e.Button = MouseButtons.Left Then DragDropResult = ListBox1.DoDragDrop( _ ListBox1.Items(ListBox1.SelectedIndex), _ DragDropEffects.Move Or DragDropEffects.Copy) ‘ If operation is a move (and not a copy), then remove then ‘ remove the item from the first list box. If DragDropResult = DragDropEffects.Move Then ListBox1.Items.RemoveAt(ListBox1.SelectedIndex) End If End If End Sub 537
ADSENSE
CÓ THỂ BẠN MUỐN DOWNLOAD
Thêm tài liệu vào bộ sưu tập có sẵn:
Báo xấu
LAVA
AANETWORK
TRỢ GIÚP
HỖ TRỢ KHÁCH HÀNG
Chịu trách nhiệm nội dung:
Nguyễn Công Hà - Giám đốc Công ty TNHH TÀI LIỆU TRỰC TUYẾN VI NA
LIÊN HỆ
Địa chỉ: P402, 54A Nơ Trang Long, Phường 14, Q.Bình Thạnh, TP.HCM
Hotline: 093 303 0098
Email: support@tailieu.vn