Visual C++大学教程第8章 菜单、工具栏和状态栏设计
Visual C++大学教程第8章 菜单、工具栏和状态栏设计

•
然后为菜单项关联命令消息处理函数 ,步骤如下。 • (1)在对话框类中添加一个消息处理函数 。
•
(2)在对话框类的消息映射部分添加 ON_COMMAND消息映射宏,将菜单 • 项的命令ID与消息处理函数关联。
• 程序设计具体步骤如下。 • (1)创建一个基于对话框的应用程序。 • (2)在主窗口中定义一个菜单成员变量。 • CMenu m_Menu;
图8.3 菜单设计窗口1
•
(4)在菜单设计窗口中,按〈Enter〉键 打开属性窗口,设计菜单标题,如图8.4所示 。
图8.4 菜单项属性窗口1
•
(5)按〈Enter〉键保存设置,返回到菜 单设计窗口,如图8.5所示。
图8.5 菜单设计窗口2
•
(6)如果用户需要设计子菜单,可以选 中下方的虚边框,按〈Enter〉键打开菜单 项属性窗口,在属性窗口中设置菜单项标 题和菜单ID,如图8.6所示。
图8.8 级联菜单
8.1.2 菜单项的命令处理
• (1)单击菜单栏中的“View”/“Class Wizard…”命令,打开MFC ClassWizard窗口 ,并选择Message Maps选项卡,在Object IDs 列表框中选择一个菜单项,如图8.20所示。
图8.20 类向导
•
(2)在该窗口的Messages列表框中双击 COMMAND,将打开“添加成员函数”窗口 ,如图8.21所示。
• BOOL ModifyMenu( UINT nPosition, UINT nFlags, UINT nIDNewItem, const CBitmap* pBmp );
(21)REMOVEMENU方法
• RemoveMenu方法用于移除一个菜
VisualBasic实用教程 薛亮 第8章.ppt

第8章 菜单的设计和MDI程序设计
2.MDI窗体上控件的设置 为了把其它的控件放入MDI窗体,应该先在MDI窗体上绘 制一个PictureBox图片框,然后在图片框中绘制其它控件。可 以在MDI窗体的图片框中使用Print方法显示文本,但是不能在 MDI窗体上显示文本。
第8章 菜单的设计和MDI程序设计
第8章 菜单的设计和MDI程序设计
(10) “有效(Enabled)”检查框,该检查框决定菜单项是否可 选(有效)。当该检查框被选中,表示菜单项的Enabled属性为 True,程序执行时菜单项高亮度显示,是可选的;如果没有被 选中,即Enabled属性为False,在程序执行时该菜单项变成灰 色,不能被用户选择。
(1) “标题(Caption)”文本框,让用户键入显示在窗体上的菜 单标题,键入的内容会在菜单编辑器窗口的下边空白部分显示 出来,该区域称为菜单显示区域。如果输入时在菜单标题的某 个字母前输入一个&符号,那么该字母就成了热键字母,在窗 体上显示时该字母有下划线,操作时同时按Alt和该带有下划线 的 字 母 就 可 选 择 这 个 菜 单 项 命 令 。 例 如 , 建 立 文 件 菜 单 File 在 “标题”文本框内应输A&File, 程序执行时用Alt+F就可以选择 File菜单。
设计快捷菜单仍然使用Visual Basic提供的菜单编辑器,只 要把某个菜单设置成隐藏Visible属性为False就可以了。实际上, 不管是在窗口顶部菜单条上显示的菜单,还是隐藏的菜单,都 可以用PopupMenu方法把它们作为快捷菜单在程序运行期间显 示出来。
第8章 菜单的设计和MDI程序设计
(4) “下一个(Next)”按钮,当用户把一个菜单项的各个属性 设置完以后,选择此按钮,即的设计和MDI程序设计
visual basic 2012 大学教程(第8章)

8. FilesConsciousness ... does not appear to itself chopped up in bits. ... A “river”or a “stream” are the metaphors by which it is most naturally described.—William JamesI can only assume that a “Do Not File” document is filed in a “Do NotFile” file.—Senator Frank Church, Senate Intelligence Subcommittee Hearing, 1975ObjectivesIn this chapter you’ll learn:• To use file processing to implement a business app.• To create, write to and read from files.• To become familia r with sequential-access file processing.• To use classes StreamWriter and StreamReader to write text to and read textfrom files.• To organize GUI commands in menus.• To manage resources with Using statements and the Finally block of a Trystatement.Outline8.1 Introduction8.2 Data Hierarchy8.3 Files and Streams8.4 Test-Driving the Credit Inquiry App8.5 Writing Data Sequentially to a Text File8.5.1 Class CreateAccounts8.5.2 Opening the File8.5.3 Managing Resources with the Using Statement8.5.4 Adding an Account to the File8.5.5 Closing the File and Terminating the App8.6 Building Menus with the Windows Forms Designer8.7Credit Inquiry App: Reading Data Sequentially from a Text File8.7.1 Implementing the Credit Inquiry App8.7.2 Selecting the File to Process8.7.3 Specifying the Type of Records to Display8.7.4 Displaying the Records8.8 Wrap-UpSummary | Terminology | Self-Review Exercises | Answers to Self-Review Exercises | Exercises8.1. IntroductionVariables and arrays offer only temporary storage of data in memory—the data is lost, for example, when a local variable ―goes out of scope‖ or when the app terminates. By contrast, files (and databases, which we cover in Chapter 12) are used for long-term retention of large (and often vast) amounts of data, even after the app that created the data terminates, so data maintained in files is often called persistent data. Computers store files on secondary storage devices, such as magnetic disks, optical disks (like CDs, DVDs and Bluray Discs™), USB flash drives and magnet ic tapes. In this chapter, we explain how to create, write to and read from data files. We continue our treatment of GUIs, explaining how to organize commands in menus and showing how to use the Windows Forms Designer to rapidly create menus. We also discuss resource management—as apps execute, they often acquire resources, such as memory and files, that need to be returned to the system so they can be reused at a later point. We show how to ensure that resources are properly returned to the system when the y’re no longer needed.8.2. Data HierarchyUltimately, all data items that computers process are reduced to combinations of 0s and 1s. This occurs because it’s simple and economical to build electronic devices that can assume two stable states—one represents 0 and the other represents 1. It’s remarkable that the impressive functions performed by computers involve only the most fundamental manipulations of 0s and 1s!BitsThe smallest data item that computers support is called a bit, short for ―binary digit‖—a digit that can assume either the value 0 or the value 1. Computer circuitry performs various simple bit manipulations, such as examining the value of a bit, setting the value of a bit and reversing a bit (from 1 to 0 or from 0 to 1). For more information on the binary number system, see Appendix C, Number Systems.CharactersProgramming with data in the low-level form of bits is cumbersome. It’s preferable to program with data in forms such as decimal digits (that is, 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9), letters (that is, the uppercase letters A–Z and the lowercase letters a–z) and special symbols (that is, $, @, %, &, *, (, ), -, +, ", :, ?, / and many others). Digits, letters and special symbols are referred to as characters. The set of all characters used to write programs and represent data items on a particular computer is called that computer’s character set. Because computers process only 0s and 1s, every character in a computer’s character set is represented as a pattern of 0s and 1s. Bytes are composed of eight bits. Visual Basic uses the Unicode character set, in which each character is typically composed of two bytes (and hence 16 bits). You create programs and data items with characters; computers manipulate and process these characters as patterns of bits. FieldsJust as characters are composed of bits, fields are composed of characters. A field is a group of characters that conveys meaning. For example, a field consisting of uppercase and lowercase letters can represent a person’s name.Data HierarchyData items processed by computers form a data hierarchy (Fig. 8.1), in which data items become larger and more complex in structure as we progress up the hierarchy from bits to characters to fields to larger data aggregates.Fig. 8.1. Data hierarchy (assuming that files are organized into records). RecordsTypically, a record is composed of several related fields. In a payroll system, for example, a record for a particular employee might include the following fields:1. Employee identification number2. Name3. Address4. Hourly pay rate5. Number of exemptions claimed6. Year-to-date earnings7. Amount of taxes withheldIn the preceding example, each field is associated with the same employee. A data file can be implemented as a group of related records.1A company’s payroll file normally contains one record for each employee. Companies typically have many files, some containing millions, billions or even trillions of characters of information.1. In some operating systems, a file is viewed as nothing more than a collection ofbytes, and any organization of the bytes in a file (such as organizing the data into records) is a view created by the programmer.To facilitate the retrieval of specific records from a file, at least one field in each record can be chosen as a record key, which identifies a record as belonging to a particular person or entity and distinguishes that record from all others. For example, in a payroll record, the employee identification number normally would be the record key. Sequential FilesThere are many ways to organize records in a file. A common organization is called a sequential file in which records typically are stored in order by a record-key field. In a payroll file, records usually are placed in order by employee identification number. DatabasesMost businesses use many different files to store data. For example, a company might have payroll files, accounts receivable files (listing money due from clients), accounts payable files (listing money due to suppliers), inventory files (listing facts about all the items handled by the business) and many other files. Related files often are stored in a database. A collection of programs designed to create and manage databases is called a database management system (DBMS). You’ll learn about databases in Chapter 12 and you’ll do additional work with databases in Chapter 13, Web App Development with , and online Chapters 24–25.8.3. Files and StreamsVisual Basic views a file simply as a sequential stream of bytes (Fig. 8.2). Depending on the operating system, each file ends either with an end-of-file marker or at a specific byte number that’s recorded in a system-maintained administrative data structure for the file. You open a file from a Visual Basic app by creating an object that enables communication between an app and a particular file, such as an object of class StreamWriter to write text to a file or an object of class StreamReader to read text from a file.Fig. 8.2. Visual Basic’s view of an n-byte file.8.4. Test-Driving the Credit Inquiry AppA credit manager would like you to implement a Credit Inquiry app that enables the credit manager to separately search for and display account information for customers with• debit balances—customers who owe the company money for previously received goods and services• credit balances—customers to whom the company owes money• zero balances—customers who do not owe the company moneyThe app reads records from a text file then displays the contents of each record that matches the type selected by the credit manager, whom we shall refer to from this point forward simply as ―the user.‖Opening the FileWhen the user initially executes the Credit Inquiry app, the Button s at the bottom of the window are disabled (Fig. 8.3(a))—the user cannot interact with them until a file has been selected. The company could have several files containing account data, so to begin processing a file of accounts, the user selects Open...from the app’s custom File menu (Fig. 8.3(b)), which you’ll create in Section 8.6. This displays an Open dialog (Fig.8.3(c)) that allows the user to specify the name and location of the file from which the records will be read. In our case, we stored the file in the folder C:\DataFiles and named the file Accounts.txt. The left side of the dialog allows the user to locate the file on disk. The user can then select the file in the right side of the dialog and click the Open Button to submit the file name to the app. The File menu also provides an Exit menu item that allows the user to terminate the app.a) Initial GUI with Buttons disabled until the user selects a file from which to readrecordsb) Selecting the Open... menu item from the File menu displays the Open dialog inpart (c)c) The Open dialog allows the user to specify the location and name of the fileFig. 8.3. GUI for the Credit Inquiry app.Displaying Accounts with Debit, Credit and Zero BalancesAfter selecting a file name, the user can click one of the Button s at the bottom of the window to display the records that match the specified account type. Figure 8.4(a) shows the accounts with debit balances. Figure 8.4(b) shows the accounts with credit balances. Figure 8.4(c) shows the accounts with zero balances.a) Clicking the Debit Balances Button displays the accounts with positive balances(that is, the people who owe the company money)b) Clicking the Credit Balances Button displays the accounts with negative balances(that is, the people to whom the company owes money)c) Clicking the Zero Balances Button displays the accounts with zero balances (that is, the people who do not have a balance because they’ve already paid or have nothad any recent transactions)Fig.8.4. GUI for Credit Inquiry app.8.5. Writing Data Sequentially to a Text FileBefore we can implement the Credit Inquiry app, we must create the file from which that app will read records. Our first app builds the sequential file containing the account information for the company’s clients. For each client, the app obtains through its GUI the c lient’s account number, first name, last name and balance—the amount of money that the client owes to the company for previously purchased goods and services. The data obtained for each client constitutes a ―record‖ for that client. In this app, the accoun t number is used as the record key—files are often maintained in order by their record keys. For simplicity, this app assumes that the user enters records in account number order.GUI for the Create Accounts AppThe GUI for the Create Accounts app is shown in Fig. 8.5. This app introduces the Menu-Strip control which enables you to place a menu bar in your window. It alsointroduces ToolStripMenuItem controls which are used to create menus and menu items. We show how use the IDE to build the menu and menu items in Section 8.6. There you’ll see that the menu and menu item variable names are generated by the IDE and begin with capital letters. Like other controls, you can change the variable names in theProperties window by modifying the (Name) property.Fig. 8.5. GUI for the Create Accounts app.Interacting with the Create Accounts AppWhen the user initially executes this app, the Close menu item, the TextBox es and the Add Account Button are disabled (Fig. 8.6(a))—the user can interact with these controls only after specifying the file into which the records will be saved. To begin creating a fileof accounts, the user selects File > New... (Fig. 8.6(b)), which displays a Save As dialog (Fig. 8.6(c)) that allows the user to specify the name and location of the file into which the records will be placed. The File menu provides two other menu items—Close to close the file so the user can create another file and Exit to terminate the app. After the user specifies a file name, the app opens the file and enables the controls, so the user can begin entering account information. Figure 8.6(d)–(h) shows the sample data being entered for five accounts. The app does not depict how the records are stored in the file. This is a text file, so after you close the app, you can open the file in any text editor to see its contents. Figure 8.6(j)shows the file’s contents in Notepad.a) Initial GUI before user selects a fileb) Selecting New... to create a filec) Save As dialog displayed when user selects New... from the File menu. In this case,the user is naming the file Accounts.txt and placing the file in the C:\DataFilesfolder.d) Creating account 100e) Creating account 200f) Creating account 300g) Creating account 400h) Creating account 500i) Closing the filej) The Accounts.txt file open in Notepad to show how the records were written to the file. Note the comma separators between the data itemsFig. 8.6. User creating a text file of account information.8.5.1. Class CreateAccountsLet’s now study the declaration of class CreateAccounts, which begins in Fig. 8.7. Framework Class Library classes are grouped by functionality into namespaces, which make it easier for you to find the classes needed to perform particular tasks. Line 3 is an Imports statement, which indicates that we’re using classes from the System.IO namespace. This namespace contains stream classes such as StreamWriter (for text output) and Stream-Reader (for text input). Line 6 declares fileWriter as an instance variable of type Stream-Writer. We’ll use this variable to interact with the file that the user selects.Click here to view code image1' Fig. 8.7: CreateAccounts.vb2' App that creates a text file of account information.3Imports System.IO ' using classes from this namespace45Public Class CreateAccounts6Dim fileWriter As StreamWriter' writes data to text file7Fig. 8.7. App that creates a text file of account information.You must import System.IO before you can use the namespace’s classes. In fact, all namespaces except System must be imported into a program to use the classes in those namespaces. Namespace System is imported by default into every program. Classes like String, Convert and Math that we’ve used frequently in earlier examples are declared in the System namespace. So far, we have not used Imports statements in any of our programs, but we have used many classes from namespaces that must be imported. For example, all of the GUI controls you’ve used so far are classes in theSystem.Windows.Forms namespace.So why were we able to compile those programs? When you create a project, each Visual Basic project type automatically imports several namespaces that are commonlyused with that project type. You can see the namespaces (Fig. 8.8) that were automatically imported into your project by right clicking the project’s name in the Solution Explorer window, selecting Properties from the menu and clicking the References tab. The list appears under Imported namespaces:—each namespace with a checkmark is automatically imported into the project. This app is a Windows Forms app. The System.IO namespace is not imported by default. To import a namespace, you can either use an Imports statement (as in line 3 of Fig. 8.7) or you can scroll through the list in Fig. 8.8 and check the checkbox for the namespace you wish to import.Fig. 8.8. Viewing the namespaces that are pre-Imported into a Windows Forms app.8.5.2. Opening the FileWhen the user selects File > New..., method NewToolStripMenuItem_Click (Fig. 8.9) is called to handle the New... m enu item’s Click event. This method opens the file. First, line 12 calls method CloseFile (Fig. 8.11, lines 102–111) in case the user previously opened another file during the current execution of the app. CloseFile closes the file associated with this app’s StreamWriter.Click here to view code image8' create a new file in which accounts can be stored9Private Sub NewToolStripMenuItem_Click(sender As Object,10 e As EventArgs) Handles NewToolStripMenuItem.Click1112 CloseFile() ' ensure that any prior file is closed13Dim result As DialogResult' stores result of Save dialog14Dim fileName As String' name of file to save data1516' display dialog so user can choose the name of the file to save17Using fileChooser As New SaveFileDialog()18 result = fileChooser.ShowDialog()19 fileName = fileChooser.FileName ' get specified file name20End Using' automatic call to fileChooser.Dispose() occurs here2122' if user did not click Cancel23If result <> Windows.Forms.DialogResult.Cancel Then24Try25' open or create file for writing26 fileWriter = New StreamWriter(fileName, True)2728' enable controls29 CloseToolStripMenuItem.Enabled = True30 addAccountButton.Enabled = True31 accountNumberTextBox.Enabled = True32 firstNameTextBox.Enabled = True33 lastNameTextBox.Enabled = True34 balanceTextBox.Enabled = True35Catch ex As IOException36 MessageBox.Show("Error Opening File", "Error",37MessageBoxButtons.OK, MessageBoxIcon.Error)38End Try39End If40End Sub' NewToolStripMenuItem_Click41Fig. 8.9. Using the SaveFileDialog to allow the user to select the file into whichrecords will be written.Next, lines 17–20 of Fig. 8.9 display the Save As dialog and get the file name specified by the user. First, line 17 creates the SaveFileDialog object (namespace System.Windows.Forms) named fileChooser. Line 18 calls its ShowDialog method to display the SaveFileDialog (Fig. 8.6(c)). This dialog prevents the user from interacting with any other window in the app until the user closes it by clicking either Save or Cancel, so it’s a modal dialog. The user selects the location where the file should be stored and specifies the file name, then clicks Save. Method ShowDialog returns a DialogResult enumeration constant specifying which button (Save or Cancel) the user clicked to close the dialog. This is assigned to the DialogResult variable result (line 18). Line 19 uses SaveFileDialog property FileName to obtain the location and name of the file.8.5.3. Managing Resources with the Using StatementLines 17–20 introduce the Using statement, which simplifies writing code in which you obtain, use and release a resource. In this case, the resource is a SaveFileDialog. Windows and dialogs are limited system resources that occupy memory and should be returned to the system (to free up that memory) as soon as they’re no longer needed. Inall our previous apps, this happens when the app terminates. In a long-running app, if resources are not returned to the system when they’re no longer needed, a resource leak occurs and the resources are not available for use in this or other apps. Objects that represent such resources typically provide a Dispose method that must be called to return the resources to the system. The Using statement in lines 17–20 creates a SaveFileDialog object, uses it in lines 18–19, then automatically calls its Dispose method to release the object’s resources as soon as End Using is reached, thusguaranteeing that the resources are returned to the system and the memory they occupy is freed up (even if an exception occurs).Line 23 tests whether the user clicked Cancel by comparing result to the constant Windows.Forms.DialogResult.Cancel. If not, line 26 creates a StreamWriter object that we’ll use to write data to the file. The two arguments are a String representing the location and name of the file, and a Boolean indicating what to do if the file already exists. If the file doesn’t exist, this statement creates the file. If the file does exist, the second argument (True) indicates that new data written to the file should be appended at the end of the file’s current contents. If the second argument is False and the file already exists, the file’s contents will be discarded and new data will be written starting at the beginning of the file. Lines 29–34 enable the Close menu item and the TextBox es and Button that are used to enter records into the app. Lines 35–37 catch an IOException if there’s a problem opening the file. If so, the app displays an error message. If no exception occurs, the file is opened for writing. Most file-processing operations have the potential to throw exceptions, so such operations are typically placed in Try statements.8.5.4. Adding an Account to the FileAfter typing information in each TextBox, the user clicks the Add Account Button, which calls method addAccountButton_Click (Fig. 8.10) to save the data into the file. If the user entered a valid account number (that is, an integer greater than zero), lines 56–59 write the record to the file by invoking the StreamWriter’s WriteLine method, which writes a sequence of characters to the file and positions the output cursor to the beginning of the next line in the file. We separate each field in the record with a comma in this example (this is known as a comma-delimited text file), and we place each record on its own line in the file. If an IOException occurs when attempting to write the record to the file, lines 64–66 Catch the exception and display an appropriate message to the user. Similarly, if the user entered invalid data in the accountNumberTextBox or balanceTextBox lines 67–69 catch the FormatExceptions thrown by class Convert’s methods and display an appropriate error message. Lines 73–77 clear the TextBox es and return the focus to the accountNumberTextBox so the user can enter the next record. Click here to view code image42' add an account to the file43Private Sub addAccountButton_Click(sender As Object,44 e As EventArgs) Handles addAccountButton.Click4546' determine whether TextBox account field is empty47If accountNumberTextBox.Text <> String.Empty Then48' try to store record to file49Try50' get account number51Dim accountNumber As Integer =52 Convert.ToInt32(accountNumberTextBox.Text)5354If accountNumber > 0Then' valid account number?55' write record data to file separating fields by commas56 fileWriter.WriteLine(accountNumber & "," &57 firstNameTextBox.Text & "," &58 lastNameTextBox.Text & "," &59 Convert.ToDecimal(balanceTextBox.Text))60Else61 MessageBox.Show("Invalid Account Number", "Error",62MessageBoxButtons.OK, MessageBoxIcon.Error)63End If64Catch ex As IOException65 MessageBox.Show("Error Writing to File", "Error",66MessageBoxButtons.OK, MessageBoxIcon.Error)67Catch ex As FormatException68 MessageBox.Show("Invalid account number or balance",69"Format Error", MessageBoxButtons.OK,MessageBoxIcon.Error)70End Try71End If7273 accountNumberTextBox.Clear()74 firstNameTextBox.Clear()75 lastNameTextBox.Clear()76 balanceTextBox.Clear()77 accountNumberTextBox.Focus()78End Sub' addAccountButton_Click79Fig. 8.10. Writing an account record to the file.8.5.5. Closing the File and Terminating the AppWhen the user selects File > Close, method CloseToolStripMenuItem_Click (Fig. 8.11, lines 81–91) calls method CloseFile (lines 102–111) to close the file. Then lines 85–90 disable the controls that should not be available when a file is not open.Click here to view code image80' close the currently open file and disable controls81Private Sub CloseToolStripMenuItem_Click(sender As Object,82 e As EventArgs) Handles CloseToolStripMenuItem.Click8384 CloseFile() ' close currently open file85 CloseToolStripMenuItem.Enabled = False86 addAccountButton.Enabled = False87 accountNumberTextBox.Enabled = False88 firstNameTextBox.Enabled = False89 lastNameTextBox.Enabled = False90 balanceTextBox.Enabled = False91End Sub' CloseToolStripMenuItem_Click9293' exit the app94Private Sub ExitToolStripMenuItem_Click(sender As Object,95 e As EventArgs) Handles ExitToolStripMenuItem.Click9697 CloseFile() ' close the file before terminating app98 Application.Exit() ' terminate the app99End Sub' ExitToolStripMenuItem_Click100101' close the file102Sub CloseFile()103If fileWriter IsNot Nothing Then104Try105 fileWriter.Close() ' close StreamWriter106Catch ex As IOException107 MessageBox.Show("Error closing file", "Error",108MessageBoxButtons.OK, MessageBoxIcon.Error)109End Try110End If111End Sub' CloseFile112End Class' CreateAccountsFig. 8.11. Closing the file and terminating the app.When the user clicks the Exit menu item, method ExitToolStripMenuItem_Click (lines 94–99) respo nds to the menu item’s Click event by exiting the app. Line 97 closes the StreamWriter and the associated file, then line 98 terminates the app. The call to method Close (line 105) is located in a Try block. Method Close throws an IOExceptionif the file cannot be closed properly. In this case, it’s important to notify the user that the information in the file or stream might be corrupted.8.6. Building Menus with the Windows Forms DesignerIn the test-drive of the Credit Inquiry app (Section 8.4) and in the overview of the Create Accounts app (Section 8.5), we demonstrated how menus provide a convenient way to organize the commands that you use to interact with an app without ―cluttering‖ its user interface. Menus contain groups of related commands. When a command is selected, the app performs a specific action (for example, select a file to open, exit the app, etc.).Menus make it simple and straightforward to locate an app’s commands. They can also make it easier for users to use apps. For example, many apps provide a File menu that contains an Exit menu item to terminate the app. If this menu item is always placed in the File menu, then users become accustomed to going to the File menu to terminate an app. When they use a new app and it has a File menu, they’ll already be familiar with the location of the Exit command.The menu that contains a menu ite m is that menu item’s parent menu. In the Create Accounts app, File is the parent menu that contains three menu items—Ne w..., Close and Exit.Adding a MenuStrip to the FormBefore you can place a menu on your app, you must provide a MenuStrip to organize and manage the app’s menus. Double click the MenuStrip control in the Toolbox. This creates a menu bar (the MenuStrip) across the top of the Form (below the title bar; Fig.8.12) and places a MenuStrip icon in the component tray (the gray area) at the bottom of the designer. You can access the MenuStrip’s properties in the Properties window by clicking the MenuStrip icon in the component tray. We set the MenuStrip’s (Name) property to applicationMenuStrip.。
VisualBasic程序设计菜单与工具栏设计

2/33
属性设置区
为了创建菜单,VB 提供了一个设计菜单的 工具,即“菜单编辑 器”。 可在VB的“工具”菜 单下选择“菜单编辑器” 命令,则可打开“菜单 编辑器”窗口。
编辑区
Visual Basic程序设计/第10章 菜单与工具栏设计
显示区
3/33
“菜单编辑器”的组成 属性设置区 窗口的上部分用于设置每个菜单项的基本属性
Visual Basic程序设计/第10章 菜单与工具栏设计
16/33
设计弹出式菜单的方法
(1)使用“菜单编辑器”窗口建立一个顶层菜单(主菜单项)。 (2)设置弹出式菜单的显示方式。使用PopupMenu方法显示弹出式菜单。 PopupMenu方法的语法格式是: [窗体名.] PopupMenu <菜单项> [, Flags [, X[, Y]]]
Visual Basic程序设计/第10章 菜单与工具栏设计
7/33
【例10-1】设计一个简单的下拉式菜单。
窗体设计界面
Visual Basic程序设计/第10章 菜单与工具栏设计
窗体执行界面
8/33
设计步骤如下:
1) 在“菜单编辑器”中建立如下菜单
标题(Caption) 体育 ….足球 menu1 menu11 名称(Name) 主菜单项 菜单命令 说明
21/33
2)设置新增对象属性:
对象 Picture1 属性 Align Caption 属性值 1-Align Top 说明 使图片框位于窗体的顶部 清空 1-Graphical 图形按钮
Command1()
Style
Picture
Caption Check1()
xg1.bmp、xg2.bmp
Visual C++基础教程课件:菜单、工具栏和状态栏

菜单、工具栏和状态栏
switch(m_nShape) { case 0:
菜单、工具栏和状态栏
添加菜单命令处理函数可以利用类向导ClassWizard。下 面给例11.1的MyDraw添加必要的代码和菜单命令处理函数, 完成应用程序的功能。
在视图类CMyDrawView的定义中添加如下的数据成员:
protected:
int m_nShape;
COLORREF m_crColor; 在视图类CMyDrawView的构造函数中对数据成员进行初 始化:
下面以实例来说明如何利用菜单编辑器创建菜单。
菜单、工具栏和状态栏
【例11.1】 编写一个单文档界面应用程序,通过菜单 选择在视图窗口中画不同的图形和设置图形的颜色。
程序的创建过程如下: (1) 利用MFC AppWizard[exe]创建SDI应用程序,项目名 设置为MyDraw。 (2) 单击项目工作区窗口下的“ResourceView”标签,打 开资源列表。展开“Menu”,双击Menu下的 IDR_MAINFRAME即可打开菜单编辑器,如图11-2所示。
void CMyDrawView::OnDrawEllipse()
{
m_nShape=0; Invalidate(); //产生WM_PAINT消息更新视图
}
菜单、工具栏和状态栏
同样为其它菜单项添加WM_COMMAND消息处理函 数如下:
void CMyDrawView::OnDrawTriangle() {
在基于MFC框架的应用程序中,可以在任何地方处理命 令消息WM_COMMAND。实际上,框架窗口是大多数命令 消息的接收者,但命令消息可以在视图类、文档类甚至在应 用程序类中被处理,只要在该类的消息映射表中添加要处理 的消息的映射项即可。从CCmdTaret派生出来的所有类都可 以处理命令消息。
c语言-菜单工具栏与状态栏

第6章 菜单、工具栏与状态栏
3
2.弹出菜单 指选择主菜单或一个菜单项时弹出的子菜单。 3.快捷菜单 当右击某个界面对象时,通常会弹出快捷菜单, 它出现在鼠标箭头的位置,快速展示当前对象可用的 命令功能。
2013/7/20
Visual C++程序设计
第6章 菜单、工具栏与状态栏
4
菜单设计一般需要经过下面两步: (1) 使用菜单编辑器编辑菜单资源; (2) 使用ClassWizard进行消息映射,编辑成员函 数,完成菜单所要实现的功能。
2013/7/20
Visual C++程序设计
第6章 菜单、工具栏与状态栏
13
“矩形”菜单的快捷键,此处仅起提示 作用,要真正成为快捷键还需要使用快 捷键编辑器进行设置
2013/7/20
Visual C++程序设计
第6章 菜单、工具栏与状态栏
14
(4) 为菜单项添加快捷键。 打开ResourceView视图中的Accelerator文件夹,双击 IDR_MAINFRAME打开快捷键编辑器。双击编辑器底 部的空白框,打开Accel Properties对话框,在ID栏下拉 列表中选择ID_RECTANGLE,在Key编辑框中输入R, 右边单选按钮接受默认值,关闭对话框。用同样的方法 为“椭圆”菜单项定义快捷键。如图所示,
2013/7/20
Visual C++程序设计
第6章 菜单、工具栏与状态栏
26
(4) 编辑快捷菜单。 展开ResourceView视图中的Menu文件夹,双击新的 菜单资源CG_IDR_POPUP_MY_DRAW_VIEW,打开菜 单资源编辑器,删除菜单POPUP下的默认菜单项。
VisualBasic程序设计基础》第8章ActiveX控件初步应用

返回 完整ppt课件
2
8.2 ActiveX控件
8.2.1ActiveX控件的使用 8.2.2 ActiveX控件的创建 8.2.3 通过向导制作ActiveX控件
返回
3
完整ppt课件
8.2.1ActiveX控件的使用
ActiveX控件使用前,必须将其添加到工具箱中。操作步骤如下:
在菜单栏上选择“工程→部件”选项,或在工具箱中单击鼠标右键,在弹出的快捷菜
ColumnHeader对象是ListView控件中包含标头文字的项目。利用ColumnHeader 对象,用户可以:
①单击对象触发ColumnClick事件并根据数据项目将项目排序。 ②拖动对象的右边框来调整列宽度。 ③在报表视图中隐藏ColumnHeader对象。 ColumnHeader对象的数目决定每个ListItem对象可包含的子项目数目。删除 ColumnHeader对象后所有与列关联的子项目也将被删除,并且每个ListItem对象的子项 目数组将平移以更新ColumnHeader的索引,而这将导致剩余的列标头SubItemIndex属 性的改变。 ColumnHeader对象的SubItemIndex属性
完整ppt课件
5
4.数状视图(TreeView)
TreeView控件显示Node对象的分层列表,每个Node对象均由一个标签和一个可选的位图
组成。TreeView一般用于显示文档标题、索引入口、磁盘上的文件和目录或能被有效地分
层显示的其它各种信息。类似于Win98的资源管理器的界面就可以用该控件来实现。
单中选择“部件”选项,弹出“部件”对话框,。该对话框中列出所有可以使用
的部件,包括“控件”、“设计器”和“可插入对象”等。
Visual C 基础教程(郭文平)章 (8)

第8章 创建应用程序框架
(6) 在“MFC AppWizard–Step 4 of 6”对话框中可以设 置应用程序的界面特征。
· Docking toolbar:缺省设置,为应用程序添加一个 标准的工具栏,且添加相应的菜单命令来显示或隐藏工具栏。
· Initial status bar:缺省设置,为应用程序添加一 个标准的状态栏,且添加相应的菜单命令来显示或隐藏状态栏。
话框,如图8-1所示。
第8章 创建应用程序框架
选择项目类型
输入项目名 选择保存路径
图8-1 New对话框的“Projects”页面
第8章 创建应用程序框架
(2) 选定“Projects”标签,在左侧项目类型列表框中选择 项目类型“MFC AppWizard[exe]”。在“Project name”文本框 中输入项目名,本例为EX8_1。在“Location”文本框中输入保 存项目的路径和文件夹名,或单击右侧的“浏览”按钮,在打开 的对话框中选择保存项目的文件夹。向导将在该文件夹下建立一 个以项目名为名称的子文件夹,用于保存此项目的所有文件。设 置完成后,单击“OK”按钮,出现“MFC AppWizard-Step 1”对 话框,如图8-2所示。
· None:默认选项,应用程序不支持任何复合文档。 · Container:应用程序作为复合文档容器,可以嵌入 或链接复合文档对象。 · Mini-server:应用程序可以创建被其它应用程序嵌 入的对象。应用程序不能作为一个独立的程序运行,只能被其 它支持嵌入对象的程序启动。 · Full-server:应用程序可以创建被其它应用程序嵌 入或链接的对象,并能作为一个独立的程序运行。 · Both container and server:应用程序既可以作为 复合文档容器,又可以作为一个可单独运行的复合文档服务器。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
图8.3 菜单设计窗口1
•
(4)在菜单设计窗口中,按〈Enter〉键 打开属性窗口,设计菜单标题,如图8.4所示 。
图8.4 菜单项属性窗口1
•
(5)按〈Enter〉键保存设置,返回到菜 单设计窗口,如图8.5所示。
图8.5 菜单设计窗口2
•
(6)如果用户需要设计子菜单,可以选 中下方的虚边框,按〈Enter〉键打开菜单 项属性窗口,在属性窗口中设置菜单项标 题和菜单ID,如图8.6所示。
(1)Attach方法
• Attach方法用于将句柄关联到菜单 对象上。 • 语法: • BOOL Attach( HMENU hMenu );
(2)DETACH方法
• Detach方法从菜单对象上分离菜单 句柄,方法返回分离的菜单句柄。 • 语法: • HMENU Detach( );
(3)FROMHANDLE方法
•
(2)在弹出的快捷菜单中选择Insert菜单项 ,打开Insert Resource窗口,如图8.2所示。
选择新添加的菜 单资源
图8.2 插入资源对话框
•
(3)在Resource type列表框中选择Menu 节点,单击“New”按钮,创建一个菜单, 如图8.3所示。
选中菜单项,按“Entຫໍສະໝຸດ r ” 键打开菜单属性窗口图8.21 添加成员函数窗口
• •
(3)单击OK按钮即可编写命令消息处理 代码,代码编辑器中将显示消息处理函数 ,如图8.22所示。
图8.22 代码编辑器
•
(4)运行程序时,当用户单击菜单项时 ,将执行其命令消息处理函数。
8.1.3 菜单项的更新机制
• 在使用类向导为菜单添加命令处理 函数时,发现菜单除了COMMAND消息外 ,还有一个UPDATE_COMMAND_UI消息 ,该消息是“更新命令用户接口消息”。
• (1)打开一个基于单文档的应用程序,运 行程序后发现“编辑”菜单下的菜单项都 不可用,如图8.23所示。
图8.23 运行结果
• (2)如果要使“编辑”菜单下的菜单项都可用 ,就要为相应的菜单项处理 UPDATE_COMMAND_ UI消息,以“撤销”菜单项为例,打开类向导, 选择Message Maps选项卡,在Class name下 拉列表中选择CMainFrame类。
• FromHandle方法根据菜单句柄返回 一个菜单对象指针。 • 语法: • static CMenu* PASCAL FromHandle( HMENU hMenu );
(4)CREATEMENU方法
• CreateMenu方法用于创建一个菜单 窗口,并将其关联到菜单对象上。 • 语法: • BOOL CreateMenu( );
(9)TRACKPOPUPMENU方法
• TrackPopupMenu方法用于显示一 个弹出式菜单。 • 语法: • BOOL TrackPopupMenu( UINT nFlags, int x, int y, CWnd* pWnd, LPCRECT lpRect = NULL );
•
在Object IDs列表框中选择“撤销 ”菜单项ID_EDIT_UNDO;在Messages 列表框中选择UPDATE_COMMAND_UI项 ,如图8.24所示。
图8.24 类向导
• (3)单击Add Function…按钮即可创建 该消息的处理函数。 • (4)单击Edit Code按钮即可定位到新建 的消息处理函数,在函数中添加代码使“ 撤销”菜单项可用。
图8.8 级联菜单
8.1.2 菜单项的命令处理
• (1)单击菜单栏中的“View”/“Class Wizard…”命令,打开MFC ClassWizard窗口 ,并选择Message Maps选项卡,在Object IDs 列表框中选择一个菜单项,如图8.20所示。
图8.20 类向导
•
(2)在该窗口的Messages列表框中双击 COMMAND,将打开“添加成员函数”窗口 ,如图8.21所示。
第8章 菜单、工具栏和状态栏设计 8.1 菜 单 设 计 • 8.1.1 菜单资源设计
• (1)在工作区的ResourceView选项卡中 ,用鼠标右键单击某个节点,将弹出一个 快捷菜单,如图8.1所示。
鼠标右键单击该节点,在 弹出的快捷菜单中选择 “Insert ”菜单项
工作区的资源视图窗口
图8.1 弹出菜单
• 代码如下: • void CMainFrame::OnUpdateEditUndo(CCm dUI* pCmdUI) • { • pCmdUI->Enable(); //使菜单项可用 • }
• (5)运行程序,效果如图8.25所示。
菜单项可用
图8.25 菜单项的更新机制
8.1.4 菜单类介绍
设置菜单项文本
设置菜单项命令 ID
图8.6 菜单项属性窗口2
•
(7)按〈Enter〉键保存设置,返回到菜 单设计窗口,如图8.7所示。
图8.7 菜单设计窗口3
•
(8)如果用户想要设计一个级联菜单, 可以在菜单项的属性窗口中选中Pop-up复 选框,这样,在菜单项的右侧将显示一个 箭头,效果如图8.8所示。
(5)CREATEPOPUPMENU方法
• CreatePopupMenu方法用于创建一 个弹出式菜单窗口,并将其关联到菜单对 象上。 • 语法: • BOOL CreatePopupMenu( );
(6)LOADMENU方法
• LoadMenu方法从应用程序的可执 行文件中加载一个菜单资源,将其关联到 菜单对象上。 • 语法: • BOOL LoadMenu( LPCTSTR lpszResourceName ); • BOOL LoadMenu( UINT nIDResource );
(7)DESTROYMENU方法
• DestroyMenu方法用于释放菜单窗口 ,当菜单窗口被释放前,它将从菜单对象上 分离出来。 • 语法: • BOOL DestroyMenu( ); •
(8)DELETEMENU方法
• DeleteMenu方法用于从菜单中删除 一个菜单项。 • 语法: • BOOL DeleteMenu( UINT nPosition, UINT nFlags );