现在的位置: 首页 > 综合 > 正文

应用程序只有一个实例C#

2013年10月30日 ⁄ 综合 ⁄ 共 1607字 ⁄ 字号 评论关闭

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

namespace DayAccount
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //防止启动多个应用和序

            if (RunningInstance() != null)
            {
                System.Windows.Forms.MessageBox.Show("已经有一个程序在运行,请双击右下角任务栏日历图标!");
                return;
            }

            FormLogin flogin = new FormLogin();
            DialogResult r= flogin.ShowDialog();
            if (r == DialogResult.OK)
            {
                Application.Run(new FormInComePayOut());
            }
        }
        //
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);

            //Loop through the running processes in with the same name
            foreach (Process process in processes)
            {
                //Ignore the current process
                if (process.Id != current.Id)
                {
                    //Make sure that the process is running from the exe file.
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName)
                    {
                        //Return the other process instance.
                        return process;
                    }
                }

            }
            //No other instance was found, return null.
            return null;

        }

        //
    }
}

抱歉!评论已关闭.