C# 右鍵選單 [CS_ContextMenuStrip]
C# 右鍵選單 [CS_ContextMenuStrip]
資料來源: https://www.itread01.com/p/623767.html
GITHUB: https://github.com/jash-git/CS_ContextMenuStrip
Form1.Designer.cs
namespace CS_ContextMenuStrip { partial class Form1 { /// <summary> /// 設計工具所需的變數。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清除任何使用中的資源。 /// </summary> /// <param name="disposing">如果應該處置 Managed 資源則為 true,否則為 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form 設計工具產生的程式碼 /// <summary> /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改 /// 這個方法的內容。 /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.SuspendLayout(); // // contextMenuStrip1 // this.contextMenuStrip1.Name = "contextMenuStrip1"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 261); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.Click += new System.EventHandler(this.Form1_Click); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; } }
Form1.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CS_ContextMenuStrip { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void toolStripMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem menu = sender as ToolStripMenuItem; MessageBox.Show(menu.Text); } private ToolStripMenuItem GetMenuItem(string txt, Image img=null) { ToolStripMenuItem menuItem = new ToolStripMenuItem(); menuItem.Text = txt; menuItem.Image = img; return menuItem; } private void BindMenu() { ToolStripMenuItem menu0 = GetMenuItem("一級1"); ToolStripMenuItem menu01 = GetMenuItem("二級11"); ToolStripMenuItem menu02 = GetMenuItem("二級12"); menu01.Click += new EventHandler(toolStripMenuItem_Click);//新增事件 menu0.DropDownItems.Add(menu01); menu0.DropDownItems.Add(menu02); contextMenuStrip1.Items.Add(menu0); ToolStripMenuItem menu1 = GetMenuItem("一級2"); ToolStripMenuItem menu11 = GetMenuItem("二級21"); ToolStripMenuItem menu12 = GetMenuItem("二級22"); menu1.DropDownItems.Add(menu11); menu1.DropDownItems.Add(menu12); contextMenuStrip1.Items.Add(menu1); } private void Form1_Click(object sender, EventArgs e) { if (((MouseEventArgs)e).Button == MouseButtons.Right) { Point p = MousePosition;//取得滑鼠位置 contextMenuStrip1.Close(); contextMenuStrip1.Show(p);//顯示右鍵選單 } } private void Form1_Load(object sender, EventArgs e) { BindMenu(); } } }