본문 바로가기
Application/C#.net

ContextMenuStrip Shortcuts

by 현이빈이 2008. 12. 8.
반응형

using System;
using System.Windows.Forms;

class Program : Form
{
    private ListBox list;

    public Program()
    {
        // Context menu for e.g. MainMenu, Toolbar, ListView etc.
        ContextMenuStrip contextMenu = new ContextMenuStrip();

        // Init items
        contextMenu.Items.Add("Add list item");
        contextMenu.Items.Add("Remove list item");
        contextMenu.Items.Add(new ToolStripSeparator());
        contextMenu.Items.Add("Show some dialog");

        // Init shortcuts
        (contextMenu.Items[0] as ToolStripMenuItem).ShortcutKeys = Keys.Insert;
        (contextMenu.Items[1] as ToolStripMenuItem).ShortcutKeys = Keys.Delete;
        (contextMenu.Items[3] as ToolStripMenuItem).ShortcutKeys = Keys.F1;

        // Events...
        contextMenu.Items[0].Click += delegate
        {
            list.Items.Add(Guid.NewGuid());
        };
        contextMenu.Items[1].Click += delegate
        {
            if (list.Items.Count > 0)
                list.Items.RemoveAt(0);
        };
        contextMenu.Items[3].Click += delegate
        {
            new MyDialog().ShowDialog(this);
        };

        // Init MainMenu
        this.MainMenuStrip = new MenuStrip();
        this.Controls.Add(this.MainMenuStrip);
        this.MainMenuStrip.Items.Add("Test 1");
        this.MainMenuStrip.Items.Add("Test 2");

        // Init items
        (this.MainMenuStrip.Items[0] as ToolStripMenuItem).DropDown = contextMenu;
        ((this.MainMenuStrip.Items[1] as ToolStripMenuItem).DropDownItems.Add("Show some dialog")
            as ToolStripMenuItem).ShortcutKeys = Keys.F2;
        (this.MainMenuStrip.Items[1] as ToolStripMenuItem).DropDownItems[0].Click += delegate
        {
            new MyDialog().ShowDialog(this);
        };

        // Sample ListBox
        list = new ListBox();
        this.Controls.Add(list);
        list.BringToFront();
        list.Dock = DockStyle.Fill;
        list.ContextMenuStrip = contextMenu;
    }

    [STAThread]
    static void Main()
    {
        Application.Run(new Program());
    }

    private class MyDialog : Form
    {
        public MyDialog()
        {
            this.Text = "Dialog Sample";
        }
    }
}

출처 : http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=2144782&SiteID=1&pageid=0

반응형