首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# WinForms 實現右鍵上下文菜單:ContextMenuStrip 完整指南

     編輯:關於C#

一、核心組件:ContextMenuStrip

.NET 2.0+ 推薦使用 ContextMenuStrip(替代舊版 ContextMenu),支持圖標、快捷鍵、分隔符、圖片、透明度、動畫等現代特性。

二、設計器可視化操作步驟

  1. 工具箱拖入 ContextMenuStrip 到窗體(底部組件欄)。
  2. 點擊組件欄中的 contextMenuStrip1,設計面板顯示菜單編輯區。
  3. 輸入菜單項文本(如「複製」「貼上」「刪除」),按 Enter 添加下一項。
  4. 右鍵菜單項可:插入分隔符、設置圖標(Image 屬性)、設置快捷鍵(ShortcutKeys)、勾選框(CheckOnClick)、子菜單(展開右側箭頭)。
  5. 選中目標控件(如 dataGridView1),屬性面板找到 ContextMenuStrip 屬性,下拉選擇 contextMenuStrip1。
  6. 運行程序,右鍵該控件即彈出菜單。

三、代碼動態創建與綁定

public partial class MainForm : Form {
    private ContextMenuStrip _gridMenu;
    private ContextMenuStrip _treeMenu;
    
    public MainForm() {
        InitializeComponent();
        CreateContextMenus();
        BindContextMenus();
    }
    
    private void CreateContextMenus() {
        // DataGridView 專用菜單
        _gridMenu = new ContextMenuStrip();
        _gridMenu.Items.Add("複製", null, (s, e) => CopyGridSelection());
        _gridMenu.Items.Add("貼上", null, (s, e) => PasteToGrid());
        _gridMenu.Items.Add(new ToolStripSeparator());
        var deleteItem = _gridMenu.Items.Add("刪除行", null, (s, e) => DeleteGridRows());
        deleteItem.ShortcutKeys = Keys.Delete;
        deleteItem.Image = Properties.Resources.DeleteIcon;
        
        // TreeView 專用菜單
        _treeMenu = new ContextMenuStrip();
        _treeMenu.Items.Add("新增子節點", null, (s, e) => AddTreeChild());
        _treeMenu.Items.Add("重命名", null, (s, e) => RenameTreeNode());
        _treeMenu.Items.Add("展開所有", null, (s, e) => treeView1.ExpandAll());
    }
    
    private void BindContextMenus() {
        dataGridView1.ContextMenuStrip = _gridMenu;
        treeView1.ContextMenuStrip = _treeMenu;
        // 也可設置窗體級:this.ContextMenuStrip = _gridMenu;
    }
    
    // 菜單事件處理示例
    private void CopyGridSelection() {
        if (dataGridView1.GetClipboardContent() is DataObject data) {
            Clipboard.SetDataObject(data);
        }
    }
}

四、進階技巧

1. 根據右鍵位置動態調整菜單項

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) {
    var cms = (ContextMenuStrip)sender;
    var dgv = cms.SourceControl as DataGridView;
    if (dgv == null) return;
    
    // 獲取點擊位置的單元格
    var hit = dgv.HitTest(dgv.PointToClient(Cursor.Position));
    bool hasSelection = dgv.SelectedCells.Count > 0;
    bool onRow = hit.RowIndex >= 0;
    
    cms.Items["複製"].Enabled = hasSelection;
    cms.Items["貼上"].Enabled = Clipboard.ContainsText();
    cms.Items["刪除行"].Enabled = onRow && !dgv.Rows[hit.RowIndex].IsNewRow;
}

2. 顯示位置微調

// 在特定位置彈出(如按鈕點擊下方)
contextMenuStrip1.Show(button1, new Point(0, button1.Height));
// 或屏幕坐標
contextMenuStrip1.Show(Cursor.Position);

3. 圖標與高 DPI

  • 設置 ImageScaling = ToolStripItemImageScaling.SizeToFit 自動縮放。
  • 高 DPI 下建議提供 16×16、24×24、32×32 多尺寸圖標,或用 SVG/矢量圖標庫。

五、常見問題排查

問題原因/解決
右鍵無反應未設置控件 ContextMenuStrip 屬性;控件 Enabled=false;被父容器攔截
菜單項事件不觸發未綁定 Click 事件;Lambda 捕獲變量問題
圖標不顯示Image 為 null;ImageTransparentColor 未設置(舊版圖標需指定透明色)
快捷鍵不生效菜單未顯示時快捷鍵不工作;衝突與主菜單/其他控件
動態添加項目不顯示在 Opening 事件中修改 Items 集合需注意線程安全

六、WPF 對應

WPF 使用 ContextMenu,支持 XAML 聲明:

<TextBox>
  <TextBox.ContextMenu>
    <ContextMenu>
      <MenuItem Header="複製" Command="Copy" />
      <MenuItem Header="貼上" Command="Paste" />
    </ContextMenu>
  </TextBox.ContextMenu>
</TextBox>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved