?????? ?可以從工具欄上拖個(gè)ContextMenu控件下來(lái),并編輯好,然后把你所需要添加ContextMenu的控件的ContextMenu屬性設(shè)為這個(gè)右鍵菜單;除了上貼所述的方法,您也可以通過(guò)手工添寫(xiě)代碼來(lái)實(shí)現(xiàn)彈出式菜單。關(guān)鍵的類是ContextMenu類。該類有兩個(gè)構(gòu)造函數(shù),其中ContextMenu()生成一個(gè)不含任何菜單項(xiàng)的彈出式菜單;ContextMenu(MenuItem[] ? menus)生成一個(gè)包括參數(shù)中所指定的菜單項(xiàng)的彈出式菜單。如要給一個(gè)按鈕控件button1添加彈出式菜單,可以參考以下的代碼: ?
? ?
? ContextMenu ? Menu1=new ? ContextMenu(); ? ?
? Menu1.MenuItems.Add(new ? MenuItem(“彈出菜單一")); ? ?
? Menu1.MenuItems.Add(new ? MenuItem(“彈出菜單二")); ? ?
? button1.ContextMenu=Menu1; ?
? ?
? ContextMenu有幾個(gè)關(guān)鍵的屬性、方法和事件,可以幫助您定制彈出式菜單,屬性RightToLeft可以使菜單項(xiàng)從右到左對(duì)齊,屬性SourceControl返回一個(gè)Control值表示當(dāng)前所顯示彈出菜單對(duì)應(yīng)的控件。Show()方法可以使程序主動(dòng)顯示彈出菜單。當(dāng)彈出菜單彈出時(shí)將引發(fā)一個(gè)Popup事件,你可以在該事件的響應(yīng)方法中進(jìn)行一些處理使彈出菜單顯示前做一些操作。 ?
? ?
? 您還可以參考MSDN中給出的一個(gè)示例來(lái)定制彈出式菜單: ?
? 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);
}
}
?