弹出唯一窗口

主窗口后台代码:

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 WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //建立集合来记录
        List<Form> AllForm = new List<Form>();

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2(this, textBox1.Text);//实例化类
            f2.Name = "f2";//重新给其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(); } } 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); } } }

弹出窗口的后台代码:

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 WindowsFormsApplication2
{
    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/123lucy/p/5845893.html