C#自定義控件添加右鍵菜單非常簡單,主要用到控件,像control定義右鍵菜單,用items.add()疊加右鍵菜單內(nèi)容,用click事件處理函數(shù)。
1、control是要定義右鍵菜單的控件。
private void control_MouseDown(object sender, MouseEventArgs e)
{
   if (e.Button == MouseButtons.Right)
   {
       ContextMenu menu = new rightClickMenu();   //初始化menu
       menu.MenuItems.Add( "c1" );   //添加菜單項(xiàng)c1
   menu.MenuItems.Add( "c2" );   //添加菜單項(xiàng)c2
       menu.Show(control, new Point(e.X, e.Y));   //在點(diǎn)(e.X, e.Y)處顯示menu
   }
}
2、添加右鍵菜單
class rightClickMenu : ContextMenuStrip
{
  //右鍵菜單
  public rightClickMenu()
  {
   Items.Add("發(fā)送消息");   //添加菜單項(xiàng)1
   Items.Add("發(fā)送文件");   //添加菜單項(xiàng)2
   Items.Add("斷開連接");   //添加菜單項(xiàng)3
   Items[0].Click += new EventHandler(sendMsg);     //定義菜單項(xiàng)1上的Click事件處理函數(shù)
   Items[1].Click += new EventHandler(sendFile);     //定義菜單項(xiàng)2上的Click事件處理函數(shù)
   Items[2].Click += new EventHandler(cutCon);     //定義菜單項(xiàng)3上的Click事件處理函數(shù)
   }
   //發(fā)送消息
   private void sendMsg(object sender, EventArgs e)
   {
}
   //發(fā)送文件
   private void sendFile(object sender, EventArgs e)
   {
}
   //斷開連接
   private void cutCon(object sender, EventArgs e)
   {
   }
}
以上內(nèi)容就是本文介紹C#自定義控件添加右鍵菜單的方法,希望大家喜歡。
新聞熱點(diǎn)
疑難解答
圖片精選