灵魂-放水

为学日益,为道日损。

BlogJava 首页 新随笔 联系 聚合 管理
  296 Posts :: 10 Stories :: 274 Comments :: 0 Trackbacks
        可以从工具栏上拖个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#)

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);
    }
 }
 
posted on 2007-03-09 14:03 放水老倌 阅读(2537) 评论(0)  编辑  收藏 所属分类: .NET

只有注册用户登录后才能发表评论。


网站导航: