C# Winform程序防止多开的三种方法

以下内容参考GPT和自己的思路。

可以通过以下几种方式来禁止winform程序多开:

  1. 使用互斥体(Mutex):在程序启动时创建一个全局的互斥体,并在程序退出时释放该互斥体。如果程序再次启动时发现互斥体已经存在,则表示程序已经在运行中,直接退出即可。

using System.Threading;
class Program
{
    static Mutex mutex = new Mutex(true, "MyMutex");
    static void Main(string[] args)
    {
        if (mutex.WaitOne(TimeSpan.Zero, true))
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            mutex.ReleaseMutex();
        }
        else
        {
            MessageBox.Show("程序已经在运行中!");
        }
    }
}
  1. 使用命名管道(Named Pipe):在程序启动时创建一个命名管道,并监听该管道的连接请求。如果程序再次启动时尝试连接该管道,则表示程序已经在运行中,直接退出即可。

using System.IO.Pipes;
class Program
{
    static NamedPipeServerStream pipeServer = new NamedPipeServerStream("MyPipe");
    static void Main(string[] args)
    {
        try
        {
            pipeServer.WaitForConnection();
            pipeServer.Disconnect();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
        catch (Exception ex)
        {
            MessageBox.Show("程序已经在运行中!");
        }
    }
}
  1. 使用文件锁(File Lock):在程序启动时创建一个文件锁,并在程序退出时释放该文件锁。如果程序再次启动时尝试获取该文件锁,则表示程序已经在运行中,直接退出即可。以上三种方式都可以实现禁止winform程序多开的效果,具体实现方式可以根据自己的需求选择。

using System.IO;
class Program
{
    static FileStream fileStream = null;
    static void Main(string[] args)
    {
        try
        {
            fileStream = new FileStream(Path.Combine(Application.StartupPath, "MyLockFile"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
        catch (IOException ex)
        {
            MessageBox.Show("程序已经在运行中!");
        }
    }
}
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值