TOOLSTRIPMENUITEM AND KEYPRESS OR KEYDOWN EVENT

jayprakash sharma

Total Post:117

Points:821
Posted by  jayprakash sharma
C# 
C#
 3368  View(s)
Ratings:
Rate this:

I am using ToolStripDropDownButton and dynamically adding menu items as below:

toolStripDropDownButton1.DropDownItems.Clear();

ToolStripMenuItem item1 = new ToolStripMenuItem("Item1");

toolStripDropDownButton1.DropDownItems.Add(item1);

ToolStripMenuItem item2 = new ToolStripMenuItem("Item2");

toolStripDropDownButton1.DropDownItems.Add(item2);

I would like to delete the selected menu item when the Delete key is pressed. But the ToolStripMenuItem doesn't have KeyPress or KeyDown event.

I am using Visual Studio 2010 and .NET 4.0. Any suggestions on how to achieve this functionality?

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: ToolStripMenuItem and KeyPress or KeyDown event

    Hi Jay,

    The enclosing ToolStrip gets the key events so you can handle it there with something like:

    toolStripDropDownButton1.KeyDown += (s, e) =>
    {
        if (e.KeyCode ==Keys.Delete)
        {
            foreach (var item in ((ToolStrip)s).Items.OfType<ToolStripMenuItem>())
            {
                if(item.Selected)
                {
                    ((ToolStrip)s).Items.Remove(item);
                    break;
                }
            }
        }
    };

      Modified On Apr-04-2018 02:07:37 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!