如何创建在按钮单击事件上实例化的winform的单个实例

如何创建在按钮单击事件上实例化的winform的单个实例

本文介绍了如何创建在按钮单击事件上实例化的winform的单个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在处理一个带有按钮的Windows应用程序表单(FormA),在button_click事件中我希望实例化另一个Windows窗体(FormB),这是来自主winform(FormA)的单独winform。我想要实例化新的实例化的winform(FormB)只有一个实例,在按钮点击事件时它不应该创建另一个winform(FormB)。除了使用FormB的单例模式之外,有没有办法做到这一点?期待逻辑方法作为答案......请给出一些选择..



我尝试过:



期待有效的方法..

m working on an windows application form(FormA) that has a button,upon button_click event i want another windows form(FormB) instantiated,which is a seperate winform from the main winform (FormA).i want to instantiate the newly instantiated winform(FormB) to have only a single instance,upon button click event it should not create another winform(FormB).is there a way to do this other than using singleton pattern for FormB??Expecting logical approach as answers...Pls give some options..

What I have tried:

expecting efficient approaches..

推荐答案

private void ButtonClick(object sender, EventArgs e)
{
    Form form = null;
    if (sender == button1)
    {
        if (Application.OpenForms[nameof(Form1)] == null)
            form = new Form1();
    }
    else // button2
    {
        if (Application.OpenForms[nameof(Form2)] == null)
            form = new Form2();
    }
    if (form != null)
    {
        form.Owner = this;
        form.Show();
    }
}


这篇关于如何创建在按钮单击事件上实例化的winform的单个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:33