当单击子窗体的菜单栏时,父窗体将被移到前面

本文关键字:窗体 前面 单击 菜单栏 | 更新日期: 2023-09-27 17:50:50

我有一个相当奇怪但可重复的问题。

我有一个MenuStrip,它可以用Form.Show()方法打开一个新的非模态表单。

子窗体也有一个菜单条。

当您开始单击子表单的菜单栏时,奇怪的事情发生了。然后父窗体回到前台,说hello。

如何防止这个问题?

一个Scorcese电影来说明我的问题,点击这个链接zippyshare.com (3Mo)

正如你在视频中看到的那样,父窗体并没有占据焦点,它只是被其他东西带到了前面。

请注意,用ToolStrip替换MenuStrip可以纠正问题。

一些重现问题的代码:

public class DemoLostfocus : Form
{
    private void InitializeComponent()
    {
        this.menuStrip1 = new MenuStrip();
        this.fileToolStripMenuItem = new ToolStripMenuItem();
        this.openModelessFormToolStripMenuItem = new ToolStripMenuItem();
        this.menuStrip1.SuspendLayout();
        this.SuspendLayout();
        this.menuStrip1.Items.AddRange(new ToolStripItem[] {
        this.fileToolStripMenuItem});
        this.menuStrip1.Location = new System.Drawing.Point(0, 0);
        this.menuStrip1.Name = "menuStrip1";
        this.menuStrip1.Size = new System.Drawing.Size(284, 24);
        this.menuStrip1.TabIndex = 0;
        this.menuStrip1.Text = "menuStrip1";
        this.fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] {
        this.openModelessFormToolStripMenuItem});
        this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
        this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
        this.fileToolStripMenuItem.Text = "File";
        this.openModelessFormToolStripMenuItem.Name = "openModelessFormToolStripMenuItem";
        this.openModelessFormToolStripMenuItem.Size = new System.Drawing.Size(187, 22);
        this.openModelessFormToolStripMenuItem.Text = "Open Modeless Form";
        this.openModelessFormToolStripMenuItem.Click += new System.EventHandler(this.openModelessFormToolStripMenuItem_Click);
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(284, 262);
        this.Controls.Add(this.menuStrip1);
        this.MainMenuStrip = this.menuStrip1;
        this.Name = "DemoLostfocus";
        this.Text = "DemoLostfocus";
        this.menuStrip1.ResumeLayout(false);
        this.menuStrip1.PerformLayout();
        this.ResumeLayout(false);
        this.PerformLayout();
    }
    private MenuStrip menuStrip1;
    private ToolStripMenuItem fileToolStripMenuItem;
    private ToolStripMenuItem openModelessFormToolStripMenuItem;
    public DemoLostfocus()
    {
        InitializeComponent();
    }
    private void openModelessFormToolStripMenuItem_Click(object sender, EventArgs e)
    {
        (new DemoLostfocus()).Show();
    }
}

当单击子窗体的菜单栏时,父窗体将被移到前面

这是。net 4.5中引入的一个非常严重的错误。知识库的文章可以在这里找到。这个修复现在只是一个热修复,希望它能很快成为一个服务更新。我只需复制/粘贴描述:

假设你有一个基于。net Framework 4.5的Windows Form应用程序。当单击菜单项打开应用程序中的子窗口时,与菜单和子窗口的交互行为不正确。

例如,您可能遇到以下情况:

当您在子窗口中打开上下文菜单时,主窗口将成为焦点。
不能使用助记符访问菜单项。

这个问题的发生是因为IMessageFilter接口被过于激进地解钩。因此,. net Framework 4.5不过滤菜单相关的窗口消息。


更新:此问题已在2013年1月8日发布的。net 4.5更新中修复。