演練:向窗體提供標准菜單項
可以通過 MenuStrip 控件為窗體提供標准菜單。
此演練演示如何使用 MenuStrip 控件創建標准菜單。 窗體還將在用戶選擇菜單項時作出響應。本演練演示了以下任務:
-
創建 Windows 窗體項目。
-
創建標准菜單。
-
創建 StatusStrip 控件。
-
處理菜單項的選擇。
完成以上步驟后,您將得到一個包含標准菜單的窗體,該窗體在一個 StatusStrip 控件中顯示菜單項的選擇情況。
若要將本主題中的代碼作為一個單獨的清單進行復制,請參見如何:向窗體提供標准菜單項。
顯示的對話框和菜單命令可能會與“幫助”中的描述不同,具體取決於您現用的設置或版本。若要更改設置,請在“工具”菜單上選擇“導入和導出設置”。 有關更多信息,請參見 使用設置。 |
若要完成本演練,您需要:
-
足以在安裝了 Visual Studio 的計算機上創建和運行 Windows 窗體應用程序項目的權限。
第一步是創建項目並設置窗體。
創建項目
-
創建一個名為“StandardMenuForm”的 Windows 應用程序項目。
有關更多信息,請參見如何:創建新的 Windows 窗體應用程序項目。
-
在 Windows 窗體設計器中,選擇該窗體。
使用 StatusStrip 控件顯示 Windows 窗體應用程序的狀態。 在本示例中,用戶選擇的菜單項顯示於 StatusStrip 控件中。
創建 StatusStrip 控件
-
從“工具箱”中將一個 StatusStrip 控件拖動到窗體上。
StatusStrip 控件自動停靠於窗體的底部。
-
單擊 StatusStrip 控件的下拉按鈕並選擇“StatusLabel”,將一個 ToolStripStatusLabel控件添加到 StatusStrip 控件中。
處理 DropDownItemClicked 事件以在用戶選擇菜單項時作出響應。
處理菜單項的選擇
-
單擊在“創建標准菜單”一節中創建的“文件”菜單項。
-
在“屬性”窗口中,單擊“事件”。
-
雙擊 DropDownItemClicked 事件。
Windows 窗體設計器為 DropDownItemClicked 事件生成一個事件處理程序。
-
將下面的代碼插入到事件處理程序中。
// This method is the DropDownItemClicked event handler. // It passes the ClickedItem object to a utility method // called UpdateStatus, which updates the text displayed // in the StatusStrip control. private void fileToolStripMenuItem_DropDownItemClicked( object sender, ToolStripItemClickedEventArgs e) { this.UpdateStatus(e.ClickedItem); }
-
將 UpdateStatus 實用工具方法的定義插入到窗體中。
// This utility method assigns the value of a ToolStripItem // control's Text property to the Text property of the // ToolStripStatusLabel. private void UpdateStatus(ToolStripItem item) { if (item != null) { string msg = String.Format("{0} selected", item.Text); this.statusStrip1.Items[0].Text = msg; } }
測試窗體
-
按 F5 編譯並運行窗體。
-
單擊“文件”菜單項以打開該菜單。
-
在“文件”菜單上,單擊其中一個菜單項以選擇該項。
StatusStrip 控件顯示了已選擇的項。
在此演練中,您創建了一個包含標准菜單的窗體。 ToolStrip 系列控件有很多其他用途:
-
使用 ContextMenuStrip 來創建控件的快捷菜單。 有關更多信息,請參見 ContextMenu 組件概述(Windows 窗體)。
-
創建包含停靠的 ToolStrip 控件的多文檔界面 (MDI) 窗體。 有關更多信息,請參見演練:創建具有菜單合並功能和 ToolStrip 控件的 MDI 窗體。
-
賦予 ToolStrip 控件專業的外觀。 有關更多信息,請參見 如何:為應用程序設置 ToolStrip 呈現程序。