?????? ?可以從工具欄上拖個ContextMenu控件下來,并編輯好,然后把你所需要添加ContextMenu的控件的ContextMenu屬性設為這個右鍵菜單;除了上貼所述的方法,您也可以通過手工添寫代碼來實現彈出式菜單。關鍵的類是ContextMenu類。該類有兩個構造函數,其中ContextMenu()生成一個不含任何菜單項的彈出式菜單;ContextMenu(MenuItem[] ? menus)生成一個包括參數中所指定的菜單項的彈出式菜單。如要給一個按鈕控件button1添加彈出式菜單,可以參考以下的代碼: ?
? ?
? ContextMenu ? Menu1=new ? ContextMenu(); ? ?
? Menu1.MenuItems.Add(new ? MenuItem(“彈出菜單一")); ? ?
? Menu1.MenuItems.Add(new ? MenuItem(“彈出菜單二")); ? ?
? button1.ContextMenu=Menu1; ?
? ?
? ContextMenu有幾個關鍵的屬性、方法和事件,可以幫助您定制彈出式菜單,屬性RightToLeft可以使菜單項從右到左對齊,屬性SourceControl返回一個Control值表示當前所顯示彈出菜單對應的控件。Show()方法可以使程序主動顯示彈出菜單。當彈出菜單彈出時將引發一個Popup事件,你可以在該事件的響應方法中進行一些處理使彈出菜單顯示前做一些操作。 ?
? ?
? 您還可以參考MSDN中給出的一個示例來定制彈出式菜單: ?
? http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWindowsFormsContextMenuClassTopic.asp?
msdn示例代碼(C#)
? ?
? ContextMenu ? Menu1=new ? ContextMenu(); ? ?
? Menu1.MenuItems.Add(new ? MenuItem(“彈出菜單一")); ? ?
? Menu1.MenuItems.Add(new ? MenuItem(“彈出菜單二")); ? ?
? button1.ContextMenu=Menu1; ?
? ?
? ContextMenu有幾個關鍵的屬性、方法和事件,可以幫助您定制彈出式菜單,屬性RightToLeft可以使菜單項從右到左對齊,屬性SourceControl返回一個Control值表示當前所顯示彈出菜單對應的控件。Show()方法可以使程序主動顯示彈出菜單。當彈出菜單彈出時將引發一個Popup事件,你可以在該事件的響應方法中進行一些處理使彈出菜單顯示前做一些操作。 ?
? ?
? 您還可以參考MSDN中給出的一個示例來定制彈出式菜單: ?
? http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWindowsFormsContextMenuClassTopic.asp?
msdn示例代碼(C#)
private void MyPopupEventHandler(System.Object sender, System.EventArgs e) { // Define the MenuItem objects to display for the TextBox. MenuItem menuItem1 = new MenuItem("&Copy"); MenuItem menuItem2 = new MenuItem("&Find and Replace"); // Define the MenuItem object to display for the PictureBox. MenuItem menuItem3 = new MenuItem("C&hange Picture"); // Clear all previously added MenuItems. contextMenu1.MenuItems.Clear(); if(contextMenu1.SourceControl == textBox1) { // Add MenuItems to display for the TextBox. contextMenu1.MenuItems.Add(menuItem1); contextMenu1.MenuItems.Add(menuItem2); } else if(contextMenu1.SourceControl == pictureBox1) { // Add the MenuItem to display for the PictureBox. contextMenu1.MenuItems.Add(menuItem3); } }?