c#中如何避免窗体的多个实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1403600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 16:08:20  来源:igfitidea点击:

How to avoid multiple instances of windows form in c#

c#singleton

提问by Anuya

How to avoid multiple instances of windows form in c# ?? i want only one instance of the form running. Because there are chances of opening the same form from many pages of my application.

如何避免在c#中出现多个windows窗体实例??我只想运行一个表单实例。因为有可能从我的应用程序的许多页面中打开相同的表单。

采纳答案by Natrium

implement the Singleton pattern

实现单例模式

an example: CodeProject: Simple Singleton Forms(ok, it's in VB.NET, but just to give you a clue)

一个例子:CodeProject: Simple Singleton Forms(好吧,它在 VB.NET 中,但只是为了给你一个线索)

回答by David Andres

You can check the existing processes prior to opening the form:

您可以在打开表单之前检查现有流程:

using System.Diagnostics;

bool ApplicationAlreadyStarted()
{
  return Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length == 0;
}

I don't know if the GetProcessesByName method is affected by UAC or other security measures.

不知道 GetProcessesByName 方法是否受到 UAC 或其他安全措施的影响。

回答by adatapost

Yes, it has singleton pattern,

是的,它有单例模式,

Code to create a singleton object,

创建单例对象的代码,

public partial class Form2 : Form
{
 .....
 private static Form2 inst;
 public static Form2  GetForm
 {
   get
    {
     if (inst == null || inst.IsDisposed)
         inst = new Form2();
     return inst;
     }
 }
 ....
}

Invoke/Show this form,

调用/显示此表单,

Form2.GetForm.Show();

回答by adatapost

Singletons are not object-oriented. They are simply the object version of global variables. What you can do is to make the constructor of the Form class private, so nobody can accidentally create one of these. Then call in reflection, convert the ctor to public and make sure you create one and only one instance of it.

单例不是面向对象的。它们只是全局变量的对象版本。您可以做的是将 Form 类的构造函数设为私有,这样任何人都不会意外地创建其中之一。然后调用反射,将 ctor 转换为 public 并确保创建它的一个且仅一个实例。

回答by Dr Herbie

If your system has the possibility of showing the same type of form for different instance data then you could create a checking system that iterates all existing open forms, looking for a unique instance data identifier and then re-display any found form.

如果您的系统有可能为不同的实例数据显示相同类型的表单,那么您可以创建一个检查系统来迭代所有现有的打开表单,寻找唯一的实例数据标识符,然后重新显示任何找到的表单。

e.g. having a form class 'CustomerDetails' which contains a public property 'CustomerUniqueID':

例如,有一个包含公共属性“CustomerUniqueID”的表单类“CustomerDetails”:

foreach(Form f in CurrentlyDisplayedForms)
{
    CustomerDetails details = f as CustomerDetails;
    if((details != null) && (details.CustomerUniqueUD == myCustomerID))
    {
        details.BringToFront();
    }
    else
    {
        CustomerDetails newDetail = new CustomerDetails(myCustomerID);
    }
}

We also use the same mechanism to automatically force refreshes of data binding where a customer's data has been edited and saved.

我们还使用相同的机制来自动强制刷新已编辑和保存客户数据的数据绑定。

回答by Muhamed Shafeeq

Try this code

试试这个代码

Public class MyClass
{
    //Create a variable named 
    public static int count = 0;
    //Then increment count variable in constructor
    MyClass()
    {
        count++;
    }
}

While creating the object for the above class 'MyClass' check the count value greater than 1

在为上述类“MyClass”创建对象时,检查计数值是否大于 1

class AnotherClass
{
    public void Event()
    {
        if(ClassName.Count <= 1)
        {
            ClassName classname=new ClassName();
        }
    }
}

回答by user2329135

Here is my solution in ShowForm() :

这是我在 ShowForm() 中的解决方案:

    private void ShowForm(Type typeofForm, string sCaption)
    {
        Form fOpen = GetOpenForm(typeofForm);
        Form fNew = fOpen;
        if (fNew == null)
            fNew = (Form)CreateNewInstanceOfType(typeofForm);
        else
            if (fNew.IsDisposed)
                fNew = (Form)CreateNewInstanceOfType(typeofForm);

        if (fOpen == null)
        {
            fNew.Text = sCaption;
            fNew.ControlBox = true;
            fNew.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            fNew.MaximizeBox = false;
            fNew.MinimizeBox = false;
            // for MdiParent
            //if (f1.MdiParent == null)
            //    f1.MdiParent = CProject.mFMain;
            fNew.StartPosition = FormStartPosition.Manual;
            fNew.Left = 0;
            fNew.Top = 0;
            ShowMsg("Ready");
        }
        fNew.Show();
        fNew.Focus();
    }
    private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
    {
        ShowForm(typeof(FAboutBox), "About");
    }

    private Form GetOpenForm(Type typeofForm)
    {
        FormCollection fc = Application.OpenForms;
        foreach (Form f1 in fc)
            if (f1.GetType() == typeofForm)
                return f1;

        return null;
    }
    private object CreateNewInstanceOfType(Type typeofAny)
    {
        return Activator.CreateInstance(typeofAny);
    }

    public void ShowMsg(string sMsg)
    {
        lblStatus.Text = sMsg;
        if (lblStatus.ForeColor != SystemColors.ControlText)
            lblStatus.ForeColor = SystemColors.ControlText;
    }

回答by Simple Man

When you display the dialog simply use .ShowDialog();instead of .Show();

当您显示对话框时,只需使用.ShowDialog();代替.Show();

回答by Vas Giatilis

One solution I applied to my project in order to bring this form again in the foreground is:

我应用于我的项目以再次将此表单置于前台的一种解决方案是:

    private bool checkWindowOpen(string windowName)
    {
        for (int i = 0; i < Application.OpenForms.Count; i++)
        {
            if (Application.OpenForms[i].Name.Equals(windowName))
            {
                Application.OpenForms[i].BringToFront();
                return false;
            }
        }
        return true;
    }

windowName is essentially the class name of your Windows Form and return value can be used for not creating a new form instance.

windowName 本质上是 Windows 窗体的类名,返回值可用于不创建新的窗体实例。

回答by Iraj

check this link:

检查此链接

using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
          {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}