控制Windows窗体的实例数 [英] Control Number of Instances of a Windows Form

查看:80
本文介绍了控制Windows窗体的实例数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主 Windows表单,只有菜单条。所有其他表单都是
继承表单,可以使用菜单条中的工具条菜单项通过
点击事件处理程序

I have a main Windows Form with just a Menu Strip. All other forms are inherited forms and can be accessed using the Tool Strip Menu Items in the Menu Strip via click event handlers.

private void toolStripMenuItemPersonnelInformation_Click(object sender, EventArgs e)
        {
            PersonnelInformation infoPersonnel = new PersonnelInformation();
            infoPersonnel.Show();
        }

如何防止启动同一表单的多个实例?我在上面的代码中添加了以下语句,以便禁用工具条菜单项。

How can I prevent multiple instances of the same form from being launched? I added the following statement to the above code in order to disable the Tool Strip Menu Item.

toolStripMenuItemPersonnelInformation.Enabled = false;

但是,它仅在主窗体中禁用,并且从未在继承的窗体中禁用。由于保护级别,我无法从继承的表单中禁用它。

However, it is only disabled in the main form and never disabled in the inherited form. I can't disable it from the inherited form due to the protection level.

谢谢,

Seif

推荐答案

创建一个类宽变量,表单显示并检查点击处理程序,如果有实际的实例,则返回此项,然后创建一个新实例:

create a class wide variable for the Form to show and check in the click handler if there's an actual instance then return this else create a new instance:

PersonnelInformation _infoPersonnel  = null;

private void toolStripMenuItemPersonnelInformation_Click(object sender, EventArgs e)
        {
            if(_infoPersonnel == null ||  _infoPersonnel.IsDisposed)
                _infoPersonnel = new PersonnelInformation();
            _infoPersonnel.Show();
        }

或在子表单中实现Singleton模式

or implement the Singleton pattern in the child-forms

问候,

  Thorsten

  Thorsten


这篇关于控制Windows窗体的实例数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆