How to stop elements in ContextMenuStrip from processing ampersands specifically?

I have ContextMenuStripone that displays elements that can be named by the user; the user is allowed to specify element names containing ampersands. When displayed ContextMenuStrip, elements treat ampersands as escape sequences and underline the next character.

I could double all ampersands before I set the elements Text, but this member is used elsewhere in the code, so if possible, I would like to stop ContextMenuStrip from processing ampersands specifically. Is there any way to disable this behavior?

+3
source share
2 answers

use &&to display one&

Edit: Sorry, I missed the second part of your question :(

You can always use string.Replace("&", "&&")in the text when setting it up, but it seems messy.

Another alternative would be to inherit from ToolStripMenuItemand override a set of text properties to replace &with &&. This will be a little better since it will save the code in one place.

+9
source

, (, UseMnemonic Button), . - , ToolStripMenuItems:

public TheForm()
{

    InitializeComponent();
    FixAmpersands(this.Controls);
}

private static void FixAmpersands(Control.ControlCollection controls)
{
    foreach (Control control in controls)
    {
        if (control is ToolStrip)
        {
            FixAmpersands((control as ToolStrip).Items);
        }
        if (control.Controls.Count > 0)
        {
            FixAmpersands(control.Controls);
        }
    }
}

private static void FixAmpersands(ToolStripItemCollection toolStripItems)
{
    foreach (ToolStripItem item in toolStripItems)
    {
        if (item is ToolStripMenuItem)
        {
            ToolStripMenuItem tsmi = (ToolStripMenuItem)item;
            tsmi.Text = tsmi.Text.Replace("&", "&&");
            if (tsmi.DropDownItems.Count > 0)
            {
                FixAmpersands(tsmi.DropDownItems);
            }
        }                
    }
}

, , , . , , , , .

0

Source: https://habr.com/ru/post/1712460/


All Articles