单击后,ContextMenuStrip不会关闭

时间:2012-09-19 14:02:36

标签: c# winforms contextmenustrip

右键单击Rich Text Box后,我将创建一个Context Menu Strip。有2个选项,一个用于更改字体,另一个用于更改背景颜色。但是,单击其中一个菜单选项后,上下文菜单条不会关闭并覆盖显示的对话框。我知道我可以让它“全球化”并迫使它关闭,但我不愿意。处理这个问题的最佳方法是什么?

// If the console is right clicked then show font options
private void rtb_console_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        ContextMenuStrip menu = new ContextMenuStrip();
        menu.Items.Add("Change Font");
        menu.Items.Add("Change Background Color");
        menu.Show(this, new Point(e.X, e.Y));
        menu.ItemClicked += new ToolStripItemClickedEventHandler(menu_ItemClicked_ChangeFont);
    }
}  

// Determine whether to change the font or the font background color
void menu_ItemClicked_ChangeFont(object sender, ToolStripItemClickedEventArgs e)
{
    Application.DoEvents();  // Read that this might help, but it doesn't
    if (e.ClickedItem.Text == "Change Font")
    {
        FontDialog font = new FontDialog();

        font.ShowColor = true;
        font.Font = rtb_console.Font;
        font.Color = rtb_console.ForeColor;

        if (font.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            rtb_console.Font = font.Font;
            rtb_console.ForeColor = font.Color;
        }
    }
    else if (e.ClickedItem.Text == "Change Background Color")
    {
        ColorDialog color = new ColorDialog();
        color.Color = rtb_console.BackColor;

        if (color.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            rtb_console.BackColor = color.Color;
        }
    }
}  

这就是发生的事情:
ContextMenuStrip Persisting

2 个答案:

答案 0 :(得分:1)

您不想创建ContextMenuStrip并且每次都手动显示它。更好的方法是创建ContextMenuStrip一次。然后通过将其分配给RichTextBox的{​​{1}}属性为ContextMenuStrip分配。这样,您每次用户点击它时都不再需要手动启动RichTextBox。它会自动发生。它还会以您点击它时的方式自动隐藏自己。

执行一次,然后删除MouseUp事件的事件处理程序:

ContextMenuStrip

此外,请不要使用ContextMenuStrip menu = new ContextMenuStrip(); menu.Items.Add("Change Font"); menu.Items.Add("Change Background Color"); menu.ItemClicked += new ToolStripItemClickedEventHandler(menu_ItemClicked_ChangeFont); rtb_console.ContextStripMenu = menu; 尝试强制UI自行更新。 Head over to here and read the top answer.一般来说,如果您使用的是Application.DoEvents();,那么您做错了什么,应该考虑改变您的做法。

您可能还会考虑做一件事,但这只是一个偏好问题......如果您使用的是Visual Studio,请考虑在设计器中创建Application.DoEvents()。这样,您可以非常轻松,直观地为每个项目添加项目,图标和单个回调。出于纯粹的个人喜好,我喜欢做的事情。

答案 1 :(得分:0)

ToolStripItemClickedEventArgs中声明:

ContextMenuStrip menu = (ContextMenuStrip)(Sender) 

if (e.ClickedItem.Text == "Change Font")
{
    menu.hide();
    /* and your code here*/...
}
相关问题