Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 82 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
82
Dung lượng
455,06 KB
Nội dung
142 Chapter 4 • Windows Forms Let’s start the walkthrough by creating a new Windows Forms project. From the main menu, choose File | New | Project, click Visual C# Projects, and choose the Windows Application template (see Figure 4.2). Change the project name to SimpleApp and click OK. Adding Controls Once we’ve created the project,Visual Studio opens the main form (Form1) in the Designer—the visual editor for our C# form class. Basically, a form created in Visual Studio is just a C# file, defining a class based on System.Windows.Forms.Form, containing code to add and configure the controls created visually.Visual Studio is a “two-way tool” meaning that we can work with the same code either visually (using the Designer) or programmatically (in the Code Editor). Let’s use the Designer to add a few controls to Form1.We can add controls and components from the toolbox window and then configure them using the Properties window. 1. From the toolbox, add a Label control to the form. By default,Visual Studio will name the control Label1. 2. From the Properties Window (F4) change label1’s Text property to Favorite CD, and change its AutoSize property to True (see Figure 4.3). This tells the control to size itself according to the metrics of the font and width of the text. www.syngress.com Figure 4.2 Creating a New Windows Forms Project Windows Forms • Chapter 4 143 3. Now add a TextBox from the toolbox onto the form, and position it below the label. Enlarge it horizontally and clear its Text property. 4. Add another label to the form, setting its Text property to Favorite Style, and AutoSize property to True. 5. Add a ComboBox and position it below the Favorite Style label. Clear its Text property. 6. Select the combo’s Items property, and then click the ellipses on the right to open the String Collection Editor.Type in a few styles of music— each on a separate line, as shown in Figure 4.4. 7. Click OK, and then press F5 to save, compile, and run the application. www.syngress.com Figure 4.3 Adding and Configuring a Label Control 144 Chapter 4 • Windows Forms www.syngress.com Figure 4.4 Populating a ComboBox Items Collection Working with Controls: Using TextBoxes To create and work with textboxes having more than one line: 1. Set MultiLine to True and AutoSize to False. 2. Set AcceptsTab and AcceptsReturn to True to allow tabs and new lines to be entered via the keyboard. 3. Set the ScrollBars property to Vertical (or Both if WordWrap is false). 4. Use the Lines property to access the control’s text one line at a time. 5. Use \r\n for a new line, for example, Flat 18\r\nQueen St. To use the control for entering a password, set the PasswordChar property to *. To read or update selected text, use the SelectionStart, SelectionLength, and SelectedText properties. Developing & Deploying… Windows Forms • Chapter 4 145 Adding an Event Handler Let’s add some functionality to the form. 1. Add a Button and ListBox to the form. 2. Select the button, and change its Text property to Update.Then click the lightning icon in the Properties window to switch to the Events View (see Figure 4.5). Think of these events as “hooks” into which we can attach our own methods.You can either double-click on an event to create a new event- handling method, or use the drop-down list to connect into an existing compatible method. 3. Double-click on the Click event.Visual Studio will write a skeleton event-handling method, wiring it to the event. It will then place you in the Code Editor, inside the empty method definition: private void button1_Click(object sender, System.EventArgs e) { } The .NET convention for event handling requires two parameters: a sender parameter of type object, and an event arguments parameter of www.syngress.com Figure 4.5 Properties Window Events View 146 Chapter 4 • Windows Forms type EventArgs—or a descendant of EventArgs.The sender parameter tells us which control fired the event (this is useful when many controls have been wired to the same event-handling method).The second parameter is designed to supply special data about the event. In the case of Click, we have a standard EventArgs object, and this contains no useful infor- mation—it’s just there to meet the protocol required to support more sophisticated events (such as KeyPress or MouseDown). The actual name for this method (button1_Click) is just a convenient identifier generated by Visual Studio;Windows Forms doesn’t impose any particular naming convention. 4. Add the following code to the event handler: private void button1_Click(object sender, System.EventArgs e) { listBox1.Items.Clear(); listBox1.Items.Add ("Fav CD: " + textBox1.Text); listBox1.Items.Add ("Fav Style: " + comboBox1.Text); } Here we’re manipulating our list box through its Items property. Items returns a collection object, having methods to add and remove items from its list. Note how we access each control through its name—this is possible because the Designer creates class fields matching the names of each con- trol.You can see these declarations at the top of the class definition. 5. Press F5 to compile and run the program (see Figure 4.6). www.syngress.com Figure 4.6 Running a Simple Windows Forms Application Windows Forms • Chapter 4 147 Adding Controls at Runtime Sometimes it’s necessary to add controls without the help of the Designer. For instance, you might want some controls to appear on a form only when a partic- ular button is clicked. In learning how to programmatically add controls, it’s very helpful to examine a visually created form in the Code Editor. If you expand the Designer Generated Code region, you’ll see a method called InitializeComponent containing all the code that creates and configures each of the form’s visual components. www.syngress.com Working with Controls: Using the ComboBox and ListBox Controls To add items to the controls’ selection lists programmatically: 1. Call the Item property’s Add method to append to the end of the list, for example: myControl.Items.Add ("My New Item"); 2. Use the Item property’s Insert method to insert within the list. 3. Because these methods expect an Object type, the item you add can be of any class, including your own (this is polymor- phism in action—one of the benefits of a working in an object-oriented language). The control simply calls the item’s ToString method to determine what to display. To get the currently selected item: 1. Use the Text property to return a string. 2. Use SelectedIndex to get a numeric position within the list. 3. Use SelectedItem to get an object reference. If the item is of your own custom class, you’ll need to explicitly cast the returned value back to your type. To allow the user to select only from items in a ComboBox list, set the DropDownStyle property to DropDownList. Developing & Deploying… 148 Chapter 4 • Windows Forms WARNING Although reading Designer-generated code is useful in understanding how components are instantiated and configured, you shouldn’t make manual changes to this code without exercising some caution. In partic- ular, you should check that the control renders as expected in the Designer before saving the form. You should also check your code after making some visual change—Visual Studio completely rewrites the Designer-generated code section, so your modifications may not appear as originally entered. Here are the four steps to programmatically adding a control or component: 1. Add a class field declaration for the new control. 2. Instantiate the control. 3. Configure the control by setting its properties and adding event han- dlers, if required. 4. Add the control to the form’s Controls collection (or alternatively, to the Controls collection of a container control, such as a GroupBox). Let’s work through an example: we’ll create a new form, add a button, and then have a textbox appear when the user clicks the button: 1. Create a new Windows Forms project called SimpleApp2 and add a Button control from the toolbox onto the new form. 2. Press F7 to open the Code Editor, and locate button1’s declaration. Below this, add a similar declaration for our new textbox, as follows (you can exclude the System.Windows.Forms prefix if your form has the appro- priate using statement): private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox myTextBox; You need to understand that this declaration doesn’t actually create a textbox.All it does is instruct the compiler, once our form is instanti- ated, to create a field that can reference (point to) a textbox object—one that does not yet exist.This declaration exists so as to provide a conve- nient way to refer to the control throughout the lifetime of the form. In the cases where we don’t need to explicitly reference the control after its been created, we can do away with this declaration. www.syngress.com Windows Forms • Chapter 4 149 3. Return to the Designer, and double-click on the button.This is a quick way to attach an event handler to the button’s default event (Click). 4. Add the following code to the button’s event handler: private void button1_Click(object sender, System.EventArgs e) { // Create the actual textbox and assign its reference to myTextBox this.myTextBox = new TextBox(); // Position the control myTextBox.Location = new Point (30, 20); // Put the control on the form. this.Controls.Add (myTextBox); } 5. Press F5 to test the application (illustrated in Figure 4.7). You might have noticed that we created a Point object to position the con- trol. Point, Size, and Rectangle are three “helper types” defined in the System.Drawing namespace, and are used extensively in Windows Forms—as well as other parts of the .NET Framework.Table 4.2 illustrates how these types are most commonly applied in Windows Forms. www.syngress.com Figure 4.7 Adding Controls at Runtime 150 Chapter 4 • Windows Forms www.syngress.com Table 4.2 Helper Types for Positioning and Sizing Type Example Notes Point struct Size struct Rectangle struct Sets button1’s position 100 pixels across and 80 pixels down. Equivalent to the above. Equivalent to out- putting button1.Left. Not permitted because of the way structs are marshaled in C#. Resizes button1 to 75 by 25 pixels. Equivalent to the above. Attempts to resize the form so it just fits button1. However, the form’s Size property includes the title bar and borders—its usable space is less, and button1 won’t quite fit. ClientSize excludes title bars and borders so this works correctly. Rectangle combines Point and Size. Moves and sizes button1 to fill the whole client area of our form (later we’ll see that docking pro- vides a better solution to achieving this). button1.Location = new Point (100, 80); button1.Left = 100; button1.Top = 80; Console.WriteLine (button1.Location.X); button1.Location.X = 100; button1.Size = new Size (75, 25); button1.Width = 75; button1.Height = 25; // Assuming "this" is our form this.Size = new Size (button1.Right, button1.Bottom); this.ClientSize = new Size (button1.Right, button1.Bottom); button1.Bounds = new Rectangle (100, 80, 50, 20); button1.Bounds = new Rectangle (0, 0, this.ClientSize.Width, this.ClientSize.Height); Windows Forms • Chapter 4 151 www.syngress.com Working with Controls: Using Controls Collections The form class is an example of a control that hosts other controls. Windows Forms manages this containership by providing a Controls property, returning a ControlCollection object that has methods to add, remove, and access the child controls. Like other .NET collections, it implements standard interfaces such as ICollection and IList—and this means we can work with them all in a similar way. To access an individual control by its position in the collection, use its Indexer—for example: Controls[0].Hide() // hide the first control in the collection To iterate through every control, use the foreach structure—for example: // Write the Text property of each control on the form foreach (Control c in Controls) Console.WriteLine (c.Text); To remove a control from the collection, use the Remove method— for example: Controls.Remove (txtMiddleName); To reparent a control to another collection: ■ Change the control’s Parent property. ■ A control’s position in the collection determines its z-order (front-to-back order), where position 0 is at the front. When you use Bring To Front and Send To Back in the Designer, you’re actually changing the control’s position in its parent’s Controls collection. You can also achieve the same thing at runtime by calling the object’s BringToFront and SendToBack methods, or by using the parent collection’s SetChildIndex method. Here are some other commonly used container-style controls that offer the same property: Developing & Deploying… Continued [...]... and change its Dock property to Left (if not already docked left) Because we’ve just put it on the form, it’ll be in front of the tree view, and will appear to its right 3 Set the list view’s Dock property to Fill (click the center rectangle in the drop-down) and then right-click the control and select Bring to Front Now it’ll be at the front, with the splitter in the middle, and the side-docked tree... nutshell, we need the following: ■ A side-docked control, at the back of the z-order ■ A splitter control, docked to the same side, in the middle of the z-order ■ A fill-docked control, at the front of the z-order We already have the two controls we want to split—all that’s required is the splitter control, and of course, everything in the right z-order 1 Set the tree view’s Dock property to Left (click the... the File menu to the child form itself, and did away with the main form entirely, we’d have a Single Document Interface (SDI) application Internet Explorer is an example of an SDI (see Figure 4.10) Figure 4.10 Single Document Interface www.syngress.com Windows Forms • Chapter 4 Creating a Multiple Document Interface In the example in the preceding section, we would prefer the editor forms to be physically... Form, name the class OptionsForm, and select DialogForm from the Inheritance Picker (see Figure 4. 13) To test this, modify the miOptions_Click method in EditForm so that it instantiates OptionsForm instead of DialogForm and run the application www.syngress.com 1 63 164 Chapter 4 • Windows Forms Figure 4. 13 Inheritance Picker Adding a TabControl When designing a form, it’s a good idea to start with a TabControl... property to True or False Adding a New Form Let’s create a new form for editing text documents: 1 Go to Project | Add Windows Form, name the class EditForm.cs, and then change the form’s Text property to Untitled 2 Drag a TextBox control from the toolbox to the form, and from the Properties windows, change its name to txtEdit 3 Clear the textbox’s Text property and change its font’s point size to 10 4 Set... 2 Change its Name property to ilSmall, and its ImageSize to 16x16 pixels—this is the size of the small icons we’ll be loading 3 Next we need to find some images to load in Search your hard drive for the Elements folder (this is usually in Program Files\Microsoft Visual Studio.NET\Common7\Graphics\Icons) 4 Expand the component’s Images collection property, and add four icons appropriate for Sun, Snow,... Populating an ImageList Note that while we’ve loaded images from ICO files, the image list control stores the data in ordinary bitmap format 5 Add a new ImageList called ilLarge, change its ImageSize to 32 x32 pixels, and repeat the previous steps (using the same icons) 6 Check that the images in the two lists appear in the same order If not, use the up and down arrow buttons in the Collection Editor to... 4.18 Adding SubItems to a ListViewItem We’ll also add an item programmatically 3 In the form’s constructor, after the call to InitializeComponent, add the following: ListViewItem lvi = new ListViewItem (new string[] { "Hail", "Possible" } ); listView1.Items.Add (lvi); 4 Run the form (see Figure 4.19) www.syngress.com 1 73 174 Chapter 4 • Windows Forms Figure 4.19 Details View at Runtime Attaching a... object containing a pointer to a method (myTextBox_MouseDown) conforming to MouseEventHandler’s signature 3 Test the application Developing & Deploying… Why We Need Delegates It’s often asked, “why can’t we simply assign a target method (for example, myTextBox_MouseDown) directly to an event?” C# doesn’t allow this because the language is strongly typed, and the event needs to pass parameters to the... side, when merged with child menus) 3 Press F7 to return to the Code Editor, and enhance the event handler for miNew as follows: private void miNew_Click(object sender, System.EventArgs e) { EditForm ef = new EditForm(); ef.MdiParent = this; // this makes ef an MDI // child form ef.Show(); } 4 Run the application.We now have an MDI (see Figure 4.11) Figure 4.11 Multiple Document Interface www.syngress.com . have a Single Document Interface (SDI) application. Internet Explorer is an example of an SDI (see Figure 4.10). www.syngress.com Figure 4.9 EditForm Menu structure Figure 4.10 Single Document Interface Windows. text. www.syngress.com Figure 4.2 Creating a New Windows Forms Project Windows Forms • Chapter 4 1 43 3. Now add a TextBox from the toolbox onto the form, and position it below the label. Enlarge it. signature. 3. Test the application. www.syngress.com Why We Need Delegates It’s often asked, “why can’t we simply assign a target method (for example, myTextBox_MouseDown) directly to an event?” C# doesn’t allow