`
473687880
  • 浏览: 484178 次
文章分类
社区版块
存档分类
最新评论

[WinForm]C# .net防止一个程序(WinForm)重复运行的方法。

 
阅读更多

最近比较忙,邮件预警系统暂停了没时间去处理,临时处理:直接执行exe文件!

可是问题来了:


我点击了两次,原来几乎在同时执行这个进程,我在程序中有线程时间睡眠2秒一次等待队列,打开进程果然两个MAIL.EXE进程,就想在执行前做一个判断阻止重复执行!

//在写一些服务型的软件的时候,你可能不希望一个操作系统里有两个副本在运行,这样也许会扰乱你的操作。这时,你就需要限制程序的副本。下面的这个方法,很简单的就可以实现上述功能。

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;

namespace TestProcessCount
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            int processCount = 0;
            Process[] pa = Process.GetProcesses();//获取当前进程数组。
            foreach (Process PTest in pa)
            {
                if (PTest.ProcessName == Process.GetCurrentProcess().ProcessName)
                {
                    processCount += 1;
                }
            }
            if (processCount > 1)
            {
                //如果程序已经运行,则给出提示。并退出本进程。
                DialogResult dr;
                dr = MessageBox.Show( Process.GetCurrentProcess().ProcessName+"程序已经在运行!", "退出程序", MessageBoxButtons.OK, MessageBoxIcon.Error);
//可能你不需要弹出窗口,在这里可以屏蔽掉
                return; //Exit;
              
            }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmBrowser());
        }
    }
}

通常会把提示信息禁止掉。一般做任务预警是在后台自动运行。。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics