如何制作单实例表单
我有一个召唤表单的 mdicontainer 表单。我的问题是,当用户再次单击该表单的菜单时,它还会创建另一个实例。
我所做的是声明一个带有公共变量的公共类,例如:Boolean isFormOneOpen = false。然后每次formOne打开时,它都会先检查我刚才声明的全局变量是否为假,如果是,则实例化一个formOne的对象,然后显示它。否则,什么也不做。非常静态,想象一下如果我有很多表单,我必须为每个表单声明一个变量来检查它是否已经打开。您能为我提供解决方案吗?也许是接受表单的方法?或者任何更聪明的方法来做到这一点。
I have a mdicontainer form that summons forms. My problem is when the a user clicks again the menu for that form, it also make another instance of it.
What I did is declare a public class with a public variable on it ex: Boolean isFormOneOpen = false. Then every time formOne opens, it checks first the global variable I declared a while ago if it's false, if it is, instantiate an object of a formOne and then show it. Otherwise, do nothing. Very static, imagine if I have many forms, I have to declare a variable for each form to check if it's already open. Can you provide me a solution for this? Maybe a method that accepts a Form? Or any more clever way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要变量,您可以迭代 MdiChildren 集合以查看表单是否已打开。例如:以
VB.NET 为中心的解决方案:
You don't need a variable, you could iterate the MdiChildren collection to see if the form is already opened. For example:
The VB.NET-centric solution:
声明表单类型的变量,而不是布尔值。然后只需确保该变量不是 Nothing 并调用它的 .Open() 方法。这有一个很好的副作用,如果现有的表单实例已经打开,它也会将其带到前面。
更好的是,在 VB.Net 2.0 及更高版本中,所有表单都有一个与其类型同名的默认实例,因此您只需说出
FormName.Open()
即可完成。不过,我以前没有在 MDI 情况下尝试过这个。Rather than a boolean, declare a variable of the form's type. Then just make sure the variable isn't Nothing and call it's .Open() method. This has the nice side effect of also bringing your existing form instance to the front if it's already open.
Even better, in VB.Net 2.0 and later all forms have a default instance with the same name as their type, so you can just say
FormName.Open()
and be done with it. However, I haven't tried this in an mdi situation before.