Menu_AppendTextItem

I have implemented the following code in my component:

protected override void AppendAdditionalComponentMenuItems(ToolStripDropDown menu)
{
    base.AppendAdditionalComponentMenuItems(menu);

    // append textbox to menu
    ToolStripTextBox toleranceItem = Menu_AppendTextItem(menu,
            this.tol.ToString(),
            (obj, e) => { },
            Menu_TextBoxChanged,
            true);
    menu.Items[5].Click += (obj, e) => ToleranceOK_Click(obj, e, toleranceItem);
}

protected void ToleranceOK_Click(object sender, EventArgs e, ToolStripTextBox tb)
{
    // do something
    // tb is null, why ?
}

For some reason tb is null in the event handler method. It is not null when it is assigned. I could swear that this code snippet worked at some point (in Rh5 ? in a previous release? I am not sure… but I am pretty sure it worked when I posted something related a year and a half ago).

Or more general: What is the recommended way to use the information provided in the text item when “commit changes” is clicked ?

That’s definitely a big no-no. The hard-coded index cannot be relied upon to always be correct.

Call the Menu_AppendTextItem() method and add both a TextChanged and KeyDown handler. If the Commit button is clicked, the KeyDown handler will be called with an Enter key, if the Cancel button is clicked you’ll get a KeyDown invoke with the Esc key.

You shouldn’t need to handle any other events, or even store the return value of the method.

Yeah I also thought that searching through the menu and somehow relying on this index is weird.

Anyways, handling KeyDown seems to work fine, thanks! I guess this is how it should look like (?):

protected void Menu_KeyDown(GH_MenuTextBox sender, KeyEventArgs e)
{
    if (e.KeyData == Keys.Enter)
    {
       // do something
    }
    else if (e.KeyData == Keys.Escape)
    {
        // do something
    }
    else
    {
        // other cases are not handled
    }
}
1 Like