我如何...创建一个单身C#表单 [英] How do i...create a singleton C# form

查看:56
本文介绍了我如何...创建一个单身C#表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#windows窗体应用程序,当我双击快捷方式时,会创建同一窗口的多个实例,但我只需要一个窗口的单个实例。

有人可以告诉我怎么做到这一点?

谢谢。



我尝试了什么:



我尝试了本视频中描述的内容:

The Singleton模式 - YouTube [ ^ ]

I have a C# windows Form application that creates multiple instances of the same window, when I double click the shortcut, but I only want one single instance of the window.
Can someone please tell me how to accomplish this?
Thanks.

What I have tried:

I tried what was described in this video:
The Singleton Pattern - YouTube[^]

推荐答案

您可以使用单例模式来确保只存在一个实例,但我认为循环遍历 Application.OpenForms属性(System.Windows.Forms) [ ^ ]。



遍历集合,检查表单是否存在,如果存在,请激活它,如果没有,则创建它。





迭代表格的示例循环

You could use a singleton pattern to ensure that only one instance exists, but I think that it would be easier just to loop through Application.OpenForms Property (System.Windows.Forms)[^].

Loop through the collection, check if the form exists and if it does, activate it, if it doesn't, create it.


An example loop to iterate through the forms
bool formOpen = false;

foreach (Form form in Application.OpenForms) {
   if (form.Name == "Form1") {
      formOpen = true;
      break;
   }
}
if (formOpen) {
   MessageBox.Show("Form is already open");
} else {
   MessageBox.Show("Form is not open");
}


我建​​议阅读过去的答案 [ ^ ]。
I'd suggest to read past answers[^].


我在program.cs中这样做了

I did this in program.cs
public static bool bf = false;
        static void Main()
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form.Name == "BatteryMonitorForm")
                {
                    bf = true;
                    break;
                }
            }
            if (!bf)
            {
                //Application.EnableVisualStyles();

                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new BatteryMonitorForm());
            }
            else { }
            
            }
            }      



它仍然不起作用,我不知道该怎么做。

你能帮忙吗?

谢谢。


And it still doesn't work, I don't know what to do.
Can you please help?
Thanks.


这篇关于我如何...创建一个单身C#表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆