winform弹出唯一的窗体

主入口窗体的后台代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace winform唯一弹窗
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        List<Form> allform = new List<Form>();
        //跳转到form2界面,把值传过去
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2(this,textBox1.Text);//实例化,把值传到form2
            f2.Name = "f2";//重新给form2的name赋值,免除发生冲突
            onlyone(f2);
        }
        //私有,保证弹出窗口是唯一的方法
        private void onlyone(Form FF)
        {
            bool hasform = false;

            foreach (Form f in allform)
            {
                if (f.Name == FF.Name)
                {
                    hasform = true;
                    f.WindowState = FormWindowState.Normal;
                    f.Focus();
                }
            }
            if (hasform)
            {
                FF.Close();
            }
            else
            {
                allform.Add(FF);
                FF.Show();
            }
        }
        //跳转到form3界面,把值传过去
        private void button2_Click(object sender, EventArgs e)
        {
            Form3 f3 = new Form3();
            f3.Name = "f3";
            onlyone(f3);
        }

        //弹窗关闭后,要在集合中移除,避免关闭后无法再次弹出
        public void removeform(Form ff)
        {
            allform.Remove(ff);
        }
    }
}

f弹出窗口form2的后台代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace winform唯一弹窗
{
    public partial class Form2 : Form
    {
        Form1 F1 = null;
        public Form2(Form1 f1,string uname)
        {
            InitializeComponent();
            F1 = f1;
            //显示用户名
            label1.Text = uname;
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            F1.removeform(this);
        }
    }
}

原文地址:https://www.cnblogs.com/sunshuping/p/5850799.html