1. Trang chủ
  2. » Công Nghệ Thông Tin

Mastering Microsoft Visual Basic 2010 phần 4 ppsx

105 564 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 105
Dung lượng 0,96 MB

Nội dung

THE RICHTEXTBOX CONTROL 283 Listing 7.13: Undoing and redoing actions Private Sub RedoToolStripMenuItem_Click(…) Handles RedoToolStripMenuItem.Click If Editor.CanRedo Then Editor().Redo() End Sub Private Sub UndoToolStripMenuItem_Click(…) Handles UndoToolStripMenuItem.Click If Editor.CanUndo Then Editor.Undo() End Sub Calling the CanUndo and CanRedo method is unnecessary; if the corresponding action can’t be performed, the two menu items will be disabled, but an additional check does no harm. The Format Menu The commands of the Format menu control the alignment and the font attributes of the current selection. The Font command displays the Font dialog box and then assigns the font selected by the user to the current selection. Listing 7.14 shows the code behind the Font command. Listing 7.14: The Font command Private Sub FontToolStripMenuItem_Click(…) Handles FontToolStripMenuItem.Click If Not Editor.SelectionFont Is Nothing Then FontDialog1.Font = Editor.SelectionFont Else FontDialog1.Font = Nothing End If FontDialog1.ShowApply = True If FontDialog1.ShowDialog() = DialogResult.OK Then Editor.SelectionFont = FontDialog1.Font End If End Sub Notice that the code preselects a font in the dialog box, the font of the current selection. If the current selection isn’t formatted with a single font, no font is preselected. To enable the Apply button of the Font dialog box, set the control’s ShowApply property to True and insert the following statement in its Apply event handler: Private Sub FontDialog1_Apply( ) Handles FontDialog1.Apply Editor.SelectionFont = FontDialog1.Font Editor.SelectionColor = FontDialog1.Color End Sub 284 CHAPTER 7 MORE WINDOWS CONTROLS The options of the Align menu set the RichTextBox control’s SelectionAlignment property to different members of the HorizontalAlignment enumeration. The Align  Left command, for example, is implemented with the following statement: Editor.SelectionAlignment = HorizontalAlignment.Left The Search & Replace Dialog Box The Find command in the Edit menu opens the dialog box shown in Figure 7.9, which performs search-and-replace operations (whole-word or case-sensitive match or both). The Search & Replace form (it’s the frmFind form in the project) has its TopMost property set to True so that it remains visible while it’s open, even if it doesn’t have the focus. The code behind the buttons on this form is quite similar to the code for the Find & Replace dialog box of the TextPad application, with one basic difference: the RTFPad project’s code uses the RichTextBox control’s Find method; the simple TextBox control doesn’t provide an equivalent method and we had to use the methods of the String class to perform the same operations. The Find method of the RichTextBox control performs all types of searches, and some of its options are not available with the IndexOf method of the String class. Figure 7.9 The Search & Replace dialog box of the RTFPad application To invoke the Search & Replace dialog box, the code calls the Show method of the frmFind form, as discussed in Chapter 5, via the following statement: frmFind.Show() The Find method of the RichTextBox control allows you to perform case-sensitive or -insensitive searches as well as search for whole words only. These options are specified throughanargumentoftheRichTextBoxFinds type. The SetSearchMode() function (see Listing 7.15) examines the settings of the two check boxes at the bottom of the form and sets the mode variable, which represents the Find method’s search mode. THE RICHTEXTBOX CONTROL 285 Listing 7.15: Setting the search options Function SetSearchMode() As RichTextBoxFinds Dim mode As RichTextBoxFinds = RichTextBoxFinds.None If chkCase.Checked = True Then mode = mode Or RichTextBoxFinds.MatchCase End If If chkWord.Checked = True Then mode = mode Or RichTextBoxFinds.WholeWord End If Return mode End Function The Click event handlers of the Find and Find Next buttons call this function to retrieve the constant that determines the type of search specified by the user on the form. This value is then passed to the Find method. Listing 7.16 shows the code behind the Find and Find Next buttons. Listing 7.16: The Find and Find Next commands Private Sub bttnFind_Click(…) Handles bttnFind.Click Dim wordAt As Integer Dim srchMode As RichTextBoxFinds srchMode = SetSearchMode() wordAt = frmEditor.Editor.Find( txtSearchWord.Text, 0, srchMode) If wordAt = -1 Then MsgBox("Can’t find word") Exit Sub End If frmEditor.Editor.Select(wordAt, txtSearchWord.Text.Length) bttnFindNext.Enabled = True bttnReplace.Enabled = True bttnReplaceAll.Enabled = True frmEditor.Editor.ScrollToCaret() End Sub Private Sub bttnFindNext_Click(…) Handles bttnFindNext.Click Dim selStart As Integer Dim srchMode As RichTextBoxFinds srchMode = SetSearchMode() selStart = frmEditor.Editor.Find( txtSearchWord.Text, frmEditor.Editor.SelectionStart + 2, srchMode) 286 CHAPTER 7 MORE WINDOWS CONTROLS If selStart = -1 Then MsgBox("No more matches") Exit Sub End If frmEditor.Editor.Select( selStart, txtSearchWord.Text.Length) frmEditor.Editor.ScrollToCaret() End Sub Notice that both event handlers call the ScrollToCaret method to force the selected text to become visible — should the Find method locate the desired string outside the visible segment of the text. The TreeView and ListView Controls The TreeView and ListView controls are among the more advanced Windows controls and they certainly are more difficult to program than the others discussed. However, these two controls are the basic makings of unique user interfaces, as you will see in the examples in the following sections. The ListView and TreeView controls are discussed in detail in the tutorial ‘‘The ListView and TreeView controls,’’ which is available for download from www.sybex.com/go/masteringvb2010. In this chapter, you will find an introduction to these two controls and their basic properties and methods. For more information on using these controls in your interface and interesting examples, please read the tutorial. Figure 7.10 shows the TreeView and ListView controls used in tandem. What you see in Figure 7.10 is Windows Explorer, a utility for examining and navigating your hard disk’s struc- ture. The left pane, where the folders are displayed, is a TreeView control. The folder names are displayed in a manner that reflects their structure on the hard disk. You can expand and con- tract certain branches and view only the segment(s) of the tree structure you’re interested in. Figure 7.10 Windows Explorer i s made up of a Tree- View (left pane) and a ListView (right pane) control. THE TREEVIEW AND LISTVIEW CONTROLS 287 The right pane is a ListView control. The items on the ListView control can be displayed in five ways (as large or small icons, as a list, on a grid, or tiled). They are the various views you can set through the View menu of Windows Explorer. Although most people prefer to look at the contents of the folders as icons, the most common view is the Details view, which displays not only filenames, but also their attributes. In the Details view, the list can be sorted according to any of its columns, making it easy for the user to locate any item based on various criteria (file type, size, creation date, and so on). Tree and List Structures The TreeView control implements a data structure known as a tree. A tree is the most appro- priate structure for storing hierarchical information. The organizational chart of a company, for example, is a tree structure. Every person reports to another person above him or her, all the way to the president or CEO. Figure 7.11 depicts a possible organization of continents, coun- tries, and cities as a tree. Every city belongs to a country, and every country to a continent. In the same way, every computer file belongs to a folder that may belong to an even bigger folder, and so on up to the drive level. You can’t draw large tree structures on paper, but it’s possible to create a similar structure in the computer’s memory without size limitations. Figure 7.11 The world viewed as a tree Globe Root node First-level nodes Second-level nodes Third-level nodes Africa Asia Europe Germany France Spain Berlin Munich Frankfurt S. America Each item in the tree of Figure 7.11 is called a node, and nodes can be nested to any level. Oddly, the top node is the root of the tree, and the subordinate nodes are called child nodes.If you try to visualize this structure as a real tree, think of it as an upside-down tree with the branches emerging from the root. The end nodes, which don’t lead to any other nodes, are called leaf nodes or end nodes. To locate a city, you must start at the root node and select the continent to which the city belongs. Then you must find the country (in the selected continent) to which the city belongs. Finally, you can find the city you’re looking for. If it’s not under the appropriate country node, it doesn’t exist. TreeView Items Are Just Strings The items displayed on a TreeView control are just strings. Moreover, the TreeView control doesn’t require that t he items be unique. You can have identically named nodes in the same branch — as unlikely as this might be for a real application. There’s no property that m akes a node unique in the tree structure or even in its own branch. 288 CHAPTER 7 MORE WINDOWS CONTROLS You can also start with a city and find its country. The country node is the city node’s parent node. Notice that there is only one route from child nodes to their parent nodes, which means that you can instantly locate the country or continent of a city. The data shown in Figure 7.11 is shown in Figure 7.12 in a TreeView control. Only the nodes we’re interested in are expanded. The plus sign indicates that the corresponding node contains child nodes. To view them, end users click the button with the plus sign and expand the node. Figure 7.12 The nodes shown in Figure 7.11 implemented with a TreeView control The tree structure is ideal for data with parent-child relations (relations that can be described as belongs to or owns). The continents-countries-cities data is a typical example. The folder struc- ture on a hard disk is another typical example. Any given folder is the child of another folder or the root folder. Maintaining a tree structure is a fundamental operation in software design; computer sci- ence students spend a good deal of their time implementing tree structures. Fortunately, with Visual Basic you don’t have to implement tree structures on your own. The TreeView control is a mechanism for storing hierarchically structured data in a control with a visible interface. The TreeView control hides (or encapsulates, in object-oriented terminology) the details of the imple- mentation and allows you to set up tree structures with a few lines of code — in short, all the gain without the pain (almost). The ListView control implements a simpler structure, known as a list. A list’s items aren’t structured in a hierarchy; they are all on the same level and can be traversed serially, one after the other. You can also think of the list as a multidimensional array, but the list offers more features. A list item can have subitems and can be sorted according to any column. For example, you can set up a list of customer names (the list’s items) and assign a number of subitems to each customer: a contact, an address, a phone number, and so on. Or you can set up a list of files with their attributes as subitems. Figure 7.13 shows a Windows folder mapped on a ListView control. Each file is an item, and its attributes are the subitems. As you already know, you can sort this list by filename, size, file type, and so on. All you have to do is click the header of the corresponding column. The ListView control is a glorified ListBox control. If all you need is a control to store sorted objects, use a ListBox control. If you want more features, such as storing multiple items per row, sorting them in different ways, or locating them based on any subitem’s THE TREEVIEW AND LISTVIEW CONTROLS 289 value, you must consider the ListView control. You can also look at the ListView control as a view-only grid. Figure 7.13 A folder’s files displayed in a ListView control (Details view) The TreeView and ListView controls are commonly used along with the ImageList control. The ImageList control is a simple control for storing images so they can be retrieved quickly and used at runtime. You populate the ImageList control with the images you want to use on your interface, usually at design time, and then you recall them by an index value at runtime. The TreeView Control Let’s start our discussion of the TreeView control with a few simple properties that you can set at design time. To experiment with the properties discussed in this section, open the Tree- ViewDemo project, available for download from www.sybex.com/go/masteringvb2010.The project’s main form is shown in Figure 7.14. After setting some properties (they are discussed next), run the project and click the Populate button to populate the control. After that, you can click the other buttons to see the effect of the various property settings on the control. Figure 7.14 The TreeViewDemo project demonstrates the basic properties and methods of the Tree- View control. 290 CHAPTER 7 MORE WINDOWS CONTROLS Here are the basic properties that determine the appearance of the control: CheckBoxes If this property is True, a check box appears in front of each node. If the con- trol displays check boxes, you can select multiple nodes; otherwise, you’re limited to a single selection. FullRowSelect This True/False value determines whether a node will be selected even if the user clicks outside the node’s caption. HideSelection This property determines whether the selected node will remain highlighted when the focus is moved to another control. By default, the selected node doesn’t remain high- lighted when the control loses the focus. HotTracking This property is another True/False value that determines whether nodes are highlighted as the pointer hovers over them. When it’s True, the TreeView control behaves like a web document with the nodes acting as hyperlinks — they turn blue while the pointer hovers over them. Use the NodeMouseHover event to detect when the pointer hovers over a node. Indent This property specifies the indentation level in pixels. The same indentation applies to all levels of the tree — each level is indented by the same number of pixels with respect to its parent level. PathSeparator A node’s full name is made up of the names of its parent nodes separated by a backslash. To use a different separator, set this property to the desired symbol. ShowLines The ShowLines property is a True/False value that determines whether the con- trol’s nodes will be connected to its parent items with lines. These lines help users visualize the hierarchy of nodes, and it’s customary to display them. ShowPlusMinus The ShowPlusMinus property is a True/False value that determines whether the plus/minus button is shown next to the nodes that have children. The plus button is dis- played when the node is collapsed, and it causes the node to expand when clicked. Likewise, the minus sign is displayed when the node is expanded, and it causes the node to collapse when clicked. Users can also expand the current node by pressing the left-arrow button and collapse it with the right-arrow button. ShowRootLines This is another True/False property that determines whether there will be lines between each node and root of the tree view. Experiment with the ShowLines and ShowRootLines properties to find out how they affect the appearance of the control. Sorted This property determines whether the items in the control will be automatically sorted. The control sorts each level of nodes separately. In our globe example, it will sort the continents, then the countries within each continent, and then the cities within each country. Adding Nodes at Design Time Let’s look now at the process of populating the TreeView control. Adding an initial collection of nodes to a TreeView control at design time is trivial. Locate the Nodes property in the Prop- erties window, and you’ll see that its value is Collection. To add items, click the ellipsis button, and the TreeNode Editor dialog box will appear, as shown in Figure 7.15. To add a root item, just click the Add Root button. The new item will be named Node0 by default. You can change its caption by selecting the item in the list and setting its Text property accordingly. You can also change the node’s Name property, and you can change the node’s appearance by using the NodeFont, FontColor,andForeColor properties. THE TREEVIEW AND LISTVIEW CONTROLS 291 Figure 7.15 The TreeNode Editor dialog box Follow these steps to enter the root node with the string Globe, a child node for Europe, and two more nodes under Europe: Germany and Italy. I’m assuming that you’re starting with a clean control. If your TreeView control contains any items, clear them all by selecting one item at a time in the list and pressing the Delete key, or click the delete button (the one with the X icon) on the dialog box. Click the Add Root button first to add the node Node0. Select it with the mouse, and its properties appear in the right pane of the TreeNode Editor window. Here you can change the node’s Text property to Globe. You can specify the appearance of each node by setting its font and fore/background colors. Then click the Add Child button, which adds a new node under the Globe root node. Select it with the mouse as before, and change its Text property to Europe. Then select the newly added node in the list and click the Add Child button again. Name the new node Germany. You’ve successfully added a small hierarchy of nodes. To add another node under Europe, select the Europe node in the list and click the Add Child button again. Name the new item Italy. Continue adding a few cities under each country to complete the tree. Click the OK button to close the TreeNode Editor’s window and return to your form. The nodes you added to the TreeView control are there, but they’re collapsed. Only the root nodes are displayed with the plus sign in front of their names. Click the plus sign to expand the tree and see its child nodes. The TreeView control behaves the same at design time as it does at runtime — as far as navigating the tree goes, at least. Adding Nodes at Runtime Adding items to the control at runtime is a bit more involved. All the nodes belong to the con- trol’s Nodes collection, which is made up of TreeNode objects. To access the Nodes collection, use the following expression, where TreeView1 is the control’s name and Nodes is a collection of TreeNode objects: TreeView1.Nodes 292 CHAPTER 7 MORE WINDOWS CONTROLS This expression returns a collection of TreeNode objects and exposes the proper members for accessing and manipulating the individual nodes. The control’s Nodes property is the collection of all root nodes. The following statements print the strings shown highlighted below them (these strings are not part of the statements; they’re the output that the statements produce): Debug.WriteLine(TreeView1.Nodes(0).Text) Globe Debug.WriteLine(TreeView1.Nodes(0).Nodes(0).Text) Europe Debug.WriteLine(TreeView1.Nodes(0).Nodes(0).Nodes(1).Text) Italy Adding New Nodes To add a new node to the Nodes collection use the Add method, which accepts as an argument a string or a TreeNode object, and returns a TreeNode object that represents the newly added node. The simplest form of the Add method is newNode = Nodes.Add(nodeCaption) where nodeCaption is a string that will be displayed on the control. Another form of the Add method allows you to add a TreeNode object directly (nodeObj is a properly initialized Tree- Node variable): newNode = Nodes.Add(nodeObj) To use this form of the method, you must first declare and initialize a TreeNode object: Dim nodeObj As New TreeNode nodeObj.Text = "Tree Node" nodeObj.ForeColor = Color.BlueViolet TreeView1.Nodes.Add(nodeObj) The last overloaded form of the Add method allows you to specify the index in the current Nodes collection, where the node will be added: newNode = Nodes.Add(index, nodeObj) The nodeObj TreeNode object must be initialized as usual. To add a child node to the root node, use a statement such as the following: TreeView1.Nodes(0).Nodes.Add("Asia") To add a country under Asia, use a statement such as the following: TreeView1.Nodes(0).Nodes(1).Nodes.Add("Japan") [...]... ColumnHeader() With {.Text New ColumnHeader() With {.Text } ListView1.Columns.AddRange(headers) ListView1.View = View.Details = = = = "Company", Width = LWidth / 4} , "Contact", Width = LWidth / 4} , "Phone", Width = LWidth / 4} , "Fax", Width = LWidth / 4} The first header corresponds to the item (not a subitem) The number of headers you set up must be equal to the number of subitems you want to display on the... item is displayed with an icon and its subitems to the right of the icon This view is available only on Windows XP and Windows Server 2003 293 2 94 CHAPTER 7 MORE WINDOWS CONTROLS The Alignment property can have one of the settings shown in Table 7 .4 Table 7 .4: Alignment property settings Setting Description Default When an item is moved on the control, the item remains where it is dropped Left Items... Chapter 14, ‘‘An Introduction to LINQ.’’ Although this is something you’ll understand better in Chapter 14, let me just mention that the team that implemented LINQ did not have access to the source of the Array class! In the following sections, you’ll learn how data and code coexist in a class and how you can manipulate the data through the properties and methods exposed by the class In Chapter 3, ‘ Visual. .. their headers You can also add columns from within your code at runtime, a topic that’s discussed in the tutorial ‘‘The ListView and TreeView Controls,’’ available for download from www.sybex.com/go/masteringvb2010 295 296 CHAPTER 7 MORE WINDOWS CONTROLS Figure 7.16 The ColumnHeader Collection Editor dialog box ListView Items and Subitems As with the TreeView control, the ListView control can be populated... determines how the items will be sorted For more information on sorting the control’s items, see the tutorial ‘‘The ListView and TreeView Controls,’’ available for download from www.sybex.com/go/masteringvb2010 Processing Selected Items The user can select multiple items from a ListView control by default Even though you can display a check mark in front of each item, it’s not customary Multiple items... Custom Windows Controls Chapter 10: Applied Object-Oriented Programming Chapter 8 Working with Objects Classes are practically synonymous with objects and they’re at the very heart of programming with Visual Basic The controls you use to build the visible interface of your application are objects, and the process of designing forms consists of setting the properties of these objects, mostly with point-and-click... and three subitems to the ListView1 control: Dim LItem As ListViewItem LItem = ListView1.Items.Add("Alfred’s Futterkiste") LItem.SubItems.Add("Maria Anders") LItem.SubItems.Add("030-00 743 21") LItem.SubItems.Add("030-0076 545 ") To access the SubItems collection, you need a reference to the item to which the subitems belong The Add method returns a reference to the newly added item, the LItem variable, which... MINIMAL CLASS Figure 8.1 Adding a class item to a project a form Start a new Windows project and name it SimpleClass (or open the SimpleClass sample project available for download from www.sybex.com/go/masteringvb2010) Then create a new class by adding a Class component to your project Right-click the project name in the Solution Explorer window and choose Add Class from the context menu In the dialog box... little The property procedure for the Age property (Listing 8 .4) throws an InvalidArgument exception if an attempt is made to assign an invalid value to it The InvalidArgument exception is one of the existing exceptions, and you can reuse it in your code Later in this chapter, you’ll learn how to create and use custom exceptions Listing 8 .4: Throwing an exception from within a property procedure Private... Line Use the OpenFileDialog and SaveFileDialog controls to prompt users for filenames Windows applications use certain controls to prompt users for common information, such as filenames, colors, and fonts Visual Studio provides a set of controls that are grouped in the Dialogs section of the Toolbox All common dialog controls provide a ShowDialog method, which displays the corresponding dialog box in a . is available for download from www.sybex.com/go/masteringvb2010. In this chapter, you will find an introduction to these two controls and their basic properties and methods. For more information. Tree- ViewDemo project, available for download from www.sybex.com/go/masteringvb2010.The project’s main form is shown in Figure 7. 14. After setting some properties (they are discussed next), run the. the control. Figure 7. 14 The TreeViewDemo project demonstrates the basic properties and methods of the Tree- View control. 290 CHAPTER 7 MORE WINDOWS CONTROLS Here are the basic properties that

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

TỪ KHÓA LIÊN QUAN