Din
Din

Reputation: 323

ToolStripMenuItem and KeyPress or KeyDown event

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?

Upvotes: 0

Views: 2547

Answers (3)

Harry
Harry

Reputation: 4946

You can use DropDown element of your menu, then bind KeyDown event to it. Now you know which key is pressed on the menu, but you don't know which menu item is pointed with mouse cursor. Bind MouseEnter event of ToolStripMenuItems and you can now store which one is pointed. Now you know which item is pointed and which key is pressed when DropDown's KeyDown event is triggered.

Upvotes: 2

mheyman
mheyman

Reputation: 4325

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;
            }
        }
    }
};

(this code is completely untested)

I used the ((ToolStrip)s) inside the event handler in case you wanted to define a static method elsewhere that could be called by multiple different ToolStrip instances. You could, of course, in this case replace ((ToolStrip)s) with toolStripDropDownButton1.

Upvotes: 0

Ira Rainey
Ira Rainey

Reputation: 5209

It sounds as if you want to delete the selected item from a dropdown list when you click on separate delete button. Is that what you're trying to do? If so then you need to be looking at the click event of the delete button and deleting the list item based upon the current selected item. KeyPress of KeyDown aren't needed.

Upvotes: 0

Related Questions