示例#1
0
        static void Main()
        {
            // Check if program is already running
            bool mutexCreated = false;
            Mutex mutex = new Mutex(true, @"Local\MouseLock.exe", out mutexCreated);

            if (!mutexCreated)
            {
                MessageBox.Show(
                    "MouseLock is already running. Only one instance is allowed.",
                    "MouseLock already running",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                mutex.Close();
                return;
            }

            // Create and start worker thread
            Worker worker = new Worker();
            worker.run();

            // Default form action
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new UI());

            // Close mutex on application exit
            mutex.Close();
        }
示例#2
0
 private bool CheckMultclient()
 {
     if (!Application.isEditor && !System.IO.File.Exists("multclient.txt"))
     {
         //禁止多开
         bool   ret      = false;
         string dataPath = Application.dataPath;
         dataPath = dataPath.Replace("\\", "/");
         dataPath = dataPath.Replace("/", "");
         mutex    = new System.Threading.Mutex(true, "glacierTTClientGameMutex", out ret);
         //创建成功
         if (ret)
         {
             mutex.ReleaseMutex();
             mutex.Close();
             ret = true;
         }
         else
         {
             GameUtil.MsgBox(System.IntPtr.Zero, "游戏已经运行!", "错误", 0x00000000 | 0x00000010);
             ret = false;
         }
         return(ret);
     }
     return(true);
 }
示例#3
0
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            bool isNewProcess = false;

            Mutex mutex = null;

            try
            {
                mutex = new Mutex(true, Application.ProductName, out isNewProcess);

                if (isNewProcess)
                {
                    Application.Run(new Snip());
                    mutex.ReleaseMutex();
                }
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.Close();
                }
            }
            // else
            // {
            //     MessageBox.Show("Another instance of " + Application.ProductName + " is already running.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            // }
        }
示例#4
0
    public static void Main(string[] args)
    {
        try {
            if (!_Mutex.WaitOne(0, false))
            {
                _Mutex.Close();
                MessageBox.Show("Another instance is already running!", VodiWikiSaver.Product);
                return;
            }

            MenuItem item = new MenuItem()
            {
                Text = "&Exit"
            };
            item.Click += new System.EventHandler(Exit_Clicked);
            ContextMenu menu = new ContextMenu();
            menu.MenuItems.Add(item);

            _TrayIcon = new NotifyIcon()
            {
                Icon        = new Icon(Assembly.GetExecutingAssembly().GetManifestResourceStream(null, "VodiWikiSaver.ico")),
                Text        = "Vodi Wiki Saver " + Version,
                ContextMenu = menu,
                Visible     = true
            };

            _WebServer = new WebServer(HttpRequest_Recieved);
            _WebServer.Run();

            Application.Run();
        }
        catch (Exception e) {
            MessageBox.Show(e.ToString(), VodiWikiSaver.Product);
        }
    }
示例#5
0
        static void Main()
        {
            Mutex mutex = new System.Threading.Mutex(false, "CWT");

            try
            {
                if (mutex.WaitOne(0, false))
                {
                    // Run the application
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new CWTNotify());
                }
                else
                {
                    MessageBox.Show("An instance of the application is already running.", "Information",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.Close();
                    mutex = null;
                }
            }
        }
        //static System.Diagnostics.Process currentProcess = null;

        /// <summary>
        /// If it return false, exit program.  (ex. call if (Application.Current != null) { Application.Current.Shutdown(); })
        /// </summary>
        public static bool TryGetMutexOnTheBeginningOfApplicationConstructor()
        {
            // Refer to: http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c
            var entryAssemblyFullName = Assembly.GetEntryAssembly().FullName;

            mutex = new System.Threading.Mutex(false, entryAssemblyFullName);
            // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
            // edited by 'Marc' to work also on localized systems (don't use just "Everyone")
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings  = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);

            if (mutex.WaitOne(TimeSpan.Zero, false))
            {
                //currentProcess = System.Diagnostics.Process.GetCurrentProcess();
                //currentProcess.Exited += (sender, e) => { ReleaseMutex(); };
                return(true);
            }

            mutex.Close();
            mutex = null;
            return(false);
        }
示例#7
0
        public void CloseMutex()
        {
            bool isNew = false;
            Mutex closeMutex = new Mutex(true, mutexName, out isNew);

            if (isNew)
            {
                Console.WriteLine("CloseMutex create a new mutex:{0}", mutexName);
            }
            else
            {
                Console.WriteLine("CloseMutex can't create a new mutex:{0}", mutexName);
            }
            closeMutex.WaitOne();

            closeMutex.ReleaseMutex();

            Console.WriteLine("CloseMutex release mutex.");

            Thread.Sleep(5000);

            closeMutex.Close();

            Console.WriteLine("Close mutex");
        }
示例#8
0
文件: FrmMain.cs 项目: TjcJose/Hi
        public FrmMain()
        {
            AppSetting.MyResourceManager = Properties.Resources.ResourceManager;
            //��������
            this.ThisAssembly = Assembly.GetExecutingAssembly();
            this.ProgramName = this.ThisAssembly.ManifestModule.Name;
            Config.AppPath = Application.StartupPath;
            Icon icoLogo = HiBLL.GetIcoLogo;
            this.Icon = icoLogo;
            ucNotifyIcon.Icon = icoLogo;
            //�����ļ�����
            this.Text = ConfigurationManager.AppSettings["ProjectName"];
            this.NameSpace = ConfigurationManager.AppSettings["ProjectNamespace"];
            AppSetting.UpdateXml = ConfigurationManager.AppSettings["UpdateXml"];
            Hi.Common.AppSetting.IniFileName = ConfigurationManager.AppSettings["SysConfigFile"];
            //gridview���б�ɫ
            Hi.Common.AppSetting.SkinStyle.RowColor = SystemColors.ControlLight;
            Config.IsDebug = false;

            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;

            mutex = new Mutex(false, this.NameSpace+"_Single_MUTEX");
            if (!mutex.WaitOne(0, false))
            {
                mutex.Close();
                mutex = null;
            }
        }
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new BackupRetentionSystemTray());
            bool createdNew = false;
            Mutex mutex = null;
            try
            {
                mutex = new Mutex(true, "BackupRetentionSystemTray", out createdNew);
            }
            catch
            {
            }
            if (mutex == null || !createdNew)
            {
                MessageBox.Show("Another instance of BackupRetentionSystemTray is already running.", "Cannot start BackupRetentionSystemTray", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                Application.Run(new BackupRetentionSystemTray());
            }
            finally
            {
                mutex.Close();
            }
        }
示例#10
0
        public static void Main()
        {
            var taken = false;
              var mutex = new Mutex(false, "qwiki.webdav.chrome");
              LocalServer server = null;

              try {
            if (!mutex.WaitOne(0)) return;
            taken = true;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            server = new LocalServer();
            server.Start();

            Application.Run();
              }
              finally {
            server?.Disconnect();
            server?.Dispose();
            if (taken) {
              mutex.Close();
            }
              }
        }
        private bool IsConsoleProcessRunning()
        {
            bool isConsoleServerRunning;

            #region Mutex avoid start twice
            Mutex mutex = new System.Threading.Mutex(false, "WindowsLivePhotoGalleryServer");
            try
            {
                //Allow only one server to run
                if (mutex.WaitOne(0, false))
                {
                    isConsoleServerRunning = false;
                }
                else
                {
                    isConsoleServerRunning = true;
                }
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.Close();
                }
            }
            #endregion
            Logger.Trace("[Windows Live Photo Gallery | Console Process] IsConsoleServerRunning: " + isConsoleServerRunning);
            return(isConsoleServerRunning);
        }
示例#12
0
文件: App.xaml.cs 项目: naiduv/Patchy
 protected override void OnStartup(StartupEventArgs e)
 {
     AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
     App.Current.DispatcherUnhandledException += (s, ex) => MessageBox.Show(ex.Exception.ToString());
     // Check for running instances of Patchy and kill them
     bool isInitialInstance;
     Singleton = new Mutex(true, "Patchy:" + SingletonGuid, out isInitialInstance);
     if (!isInitialInstance)
         KillCurrentInstance();
     Singleton.Close();
     // Check for permissions
     if (!Patchy.UacHelper.IsProcessElevated && !Debugger.IsAttached)
     {
         var info = new ProcessStartInfo(Assembly.GetEntryAssembly().Location);
         info.Verb = "runas";
         Process.Start(info);
         Application.Current.Shutdown();
         return;
     }
     // Check for .NET 4.0
     var value = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", "Install", null);
     if (value == null)
     {
         var result = MessageBox.Show("You must install .NET 4.0 to run Patchy. Would you like to do so now?",
             "Error", MessageBoxButton.YesNo, MessageBoxImage.Error);
         if (result == MessageBoxResult.Yes)
             Process.Start("http://www.microsoft.com/en-us/download/details.aspx?id=17851");
         Application.Current.Shutdown();
         return;
     }
 }
示例#13
0
        static void Main()
        {
            Mutex _mutex = new System.Threading.Mutex(false, "SO2RInterface");

            try
            {
                if (_mutex.WaitOne(0, false))
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form());
                }
                else
                {
                    //MessageBox.Show("An instance of the application is already running.");
                }
            }
            finally
            {
                if (_mutex != null)
                {
                    _mutex.Close();
                }
            }
        }
示例#14
0
        /// <summary>
        /// Start controlling the application
        /// </summary>
        public void StartApp()
        {
            this._NativeResource = Marshal.AllocHGlobal(100);

            // Enable XP styles
            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);

            // Setup unhandled exception handlers
            AppDomain.CurrentDomain.UnhandledException += // CLR
               new UnhandledExceptionEventHandler(OnUnhandledException);
            Application.ThreadException += // Windows Forms
                new ThreadExceptionEventHandler(OnGuiUnhandedException);

            // Create an application Context
            this._AppContext = new ApplicationContext();

            // Start by showing the main application screen
            this.MainView_Show();

            // Single instance checked
            bool IsFirstInstance;
            Mutex theMutex = new Mutex(false, "Local\\Karaokidex", out IsFirstInstance);

            /* If IsFirstInstance is now true, we're the first instance of the application; 
             * otherwise another instance is running.
             */
            if (IsFirstInstance)
            {
                Application.Run(this._AppContext);
            }
            theMutex.Close();
            Application.Exit(); 
        }
        public static bool AlreadyRunning(string mutexName)
        {
            long runningId = 50000;
            bool InstanceRunning = false;

            Process proc = Process.GetCurrentProcess();
            Process[] runningProcesses = Process.GetProcesses();

            foreach (Process p in runningProcesses) {
                if (p.Id != proc.Id) {
                    bool Created = false;
                    mutex = new Mutex(true, mutexName + p.Id.ToString(), out Created);
                    if (!Created) {
                        InstanceRunning = true;
                        runningId = p.Id;
                        break;
                    } else {
                        mutex.Close();
                    }
                }
            }
            if (InstanceRunning) {
                IntPtr hWnd = Process.GetProcessById((int)runningId).MainWindowHandle;
                if (NativeMethods.IsIconic(hWnd)) {
                    NativeMethods.ShowWindowAsync(hWnd, 9);
                }
                NativeMethods.SetForegroundWindow(hWnd);
            } else {
                mutex = new Mutex(true, mutexName + proc.Id.ToString());
            }
            return InstanceRunning;
        }
示例#16
0
 static void Main()
 {
     Mutex mutex = new System.Threading.Mutex(false, "GUI");
     try
     {
         if (mutex.WaitOne(0, false))
         {
             // Run the application
             Application.EnableVisualStyles();
             Application.SetCompatibleTextRenderingDefault(false);
             Application.Run(new frmMain());
         }
         else
         {
             MessageBox.Show("Reminiscent is already running!", "Reminiscent");
         }
     }
     finally
     {
         if (mutex != null)
         {
             mutex.Close();
             mutex = null;
         }
     }
 }
示例#17
0
    void ReStartApplication()
    {
        ForbidQuit = false;
        Application.Quit();

        string LauncherPath = Application.dataPath;

        LauncherPath = LauncherPath.Replace("\\", "/");
        LauncherPath = LauncherPath.Replace("Bin/neice/TTClient_Data", string.Empty);

        ProcessStartInfo info = new ProcessStartInfo();

        info.WorkingDirectory = LauncherPath;
        LauncherPath         += "泰坦.exe";
        info.FileName         = LauncherPath;

        if (System.IO.File.Exists(LauncherPath))
        {
            if (null != mutex)
            {
                mutex.Close();
                mutex = null;
            }
            if (null == Process.Start(info))
            {
                UnityEngine.Debug.LogWarning("启动器:" + LauncherPath);
                GameUtil.MsgBox(m_WindowHwnd, "启动游戏失败,请手动启动游戏", "提示", 0);
            }
        }
        else
        {
            UnityEngine.Debug.LogWarning("找不到启动器:" + LauncherPath + ",启动失败");
        }
    }
示例#18
0
        /// <summary>Check if it is the first application instance.</summary>
        /// <param name="instanceName">Unique instance name. If null, executanle path is used.</param>
        /// <param name="isGlobal">Check globally, for all terminal sessions.</param>
        public static bool IsFirstInstance (string instanceName = null, bool isGlobal = true)
        {
            if (instanceName != null && instanceName.Contains("\\"))
                throw new ArgumentException("name");
            if (instanceName == null)
                instanceName = Paths.ExecutableFilePath.Replace('\\', '/');
            string newMutexName = isGlobal ? GlobalNamespacePrefix + instanceName : instanceName;
            lock (sync) {
                // can only be called with the same name
                if (!string.IsNullOrEmpty(mutexName) && string.CompareOrdinal(mutexName, newMutexName) != 0)
                    throw new ArgumentException("Must be unique for application.", "instanceName");
                // has already checked
                if (mutex != null)
                    return true;
                mutexName = newMutexName;

                bool isNew;
                try {
                    // try to create mutex with full permissions
                    mutex = new Mutex(true, mutexName, out isNew, CreateFullAccessMutexSecurity());
                }
                catch (UnauthorizedAccessException) {
                    // not new, another instance created mutex with limited permissions
                    return false;
                }
                if (!isNew) {
                    // not new, another instance exists
                    mutex.Close();
                    mutex = null;
                }
                return isNew;
            }
        }
示例#19
0
        static void Main()
        {
            Mutex SingleInstanceMutex;
            try
            {
                SingleInstanceMutex = Mutex.OpenExisting("daash");
            }
            catch (Exception)
            {
                SingleInstanceMutex = new Mutex(false, "daash");
            }

            try
            {
                if (SingleInstanceMutex.WaitOne(0, false))
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new MainForm());
                }
                else
                {
                    MessageBox.Show("It is only possible to run one instance of daash", "daash is already running", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                if (SingleInstanceMutex != null)
                {
                    SingleInstanceMutex.Close();
                    SingleInstanceMutex = null;
                }
            }
        }
示例#20
0
        static void Main()
        {
            try
            {
                // ミューテックスを生成する
                mutexObject = new Mutex(false, strAppConstName);
            }
            catch (ApplicationException e)
            {
                // グローバル・ミューテックスによる多重起動禁止
                MessageBox.Show("すでに起動しています。NanoTermを2つ同時には起動できません。", "多重起動エラー");
                return;
            }

            // ミューテックスを取得する
            if (mutexObject.WaitOne(0, false))
            {
                // アプリケーションを実行

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm());

                // ミューテックスを解放する
                mutexObject.ReleaseMutex();
            }
            else
            {
                //  警告を表示して終了
                MessageBox.Show("すでに起動しています。NanoTermを2つ同時には起動できません。", "多重起動エラー");
            }

            // ミューテックスを破棄する
            mutexObject.Close();
        }
示例#21
0
        private static bool DoubleProcess()
        {
            bool ok = true;
            //Mutex名を決める(必ずアプリケーション固有の文字列に変更すること!)
            string mutexName = "AzureFileWatch";

            bool hasHandle = false;

            //Mutexオブジェクトを作成する
            System.Threading.Mutex mutex = new System.Threading.Mutex(true, mutexName, out hasHandle);

            try
            {
                //ミューテックスを得られたか調べる
                if (hasHandle == false)
                {
                    //得られなかった場合は、すでに起動していると判断して終了
                    Console.WriteLine("多重起動はできません。");
                    Console.ReadKey();
                    ok = false;
                }
            }
            finally
            {
                if (hasHandle)
                {
                    //ミューテックスを解放する
                    mutex.ReleaseMutex();
                }
                mutex.Close();
            }
            return(ok);
        }
示例#22
0
        static void Main()
        {
            Mutex mutex     = new System.Threading.Mutex(false, mutexName);
            bool  hasHandle = false;

            try {
                //多重起動の抑止
                try {
                    hasHandle = mutex.WaitOne(0, false);
                } catch (AbandonedMutexException) {
                    hasHandle = true;
                }

                if (hasHandle == false)
                {
                    return;
                }

                //フック開始
                StartHook();
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run();
            } catch (Exception e) {
                MessageBox.Show(e.Message);
            } finally {
                EndHook();

                if (hasHandle)
                {
                    mutex.ReleaseMutex();
                }
                mutex.Close();
            }
        }
示例#23
0
文件: Program.cs 项目: Winsor/ITInfra
        private static void Main()
        { 
#if DEBUG
            //EFlogger.EntityFramework6.EFloggerFor6.Initialize();  
#endif
            Mutex runOnce = null;
            try
            {
                runOnce = new Mutex(true, "Events_V2_Application_Mutex");
                if (runOnce.WaitOne(TimeSpan.Zero))
                {
                    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                    Application.ThreadException += ExceptionHandler.ThreadExceptionHandler;
                    AppDomain.CurrentDomain.UnhandledException += ExceptionHandler.UnhandledExceptionHandler;
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new EventsMainForm());
                }
                else
                {
                    InfoForm info = new InfoForm()
                    {
                        InfoMessage = {Text = @"Приложение уже запущено!"}
                    };
                    info.ShowDialog();
                }
            }
            finally
            {
                if (null != runOnce)
                    runOnce.Close();
            }
        }
示例#24
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            AppPath = (Application.StartupPath.ToLower());
            AppPath = AppPath.Replace(@"\bin\debug", @"\").Replace(@"\bin\release", @"\");
            AppPath = AppPath.Replace(@"\bin\x86\debug", @"\").Replace(@"\bin\x86\release", @"\");

            AppPath = AppPath.Replace(@"\\", @"\");

            if (!AppPath.EndsWith(@"\"))
                AppPath += @"\";

            if (args.Length > 0)
            {
                ProgramName = args[0];
                AppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\" + ProgramName +
                              @"\";
                bool firstInstance;
                var mutex = new Mutex(false, "iSpyMonitor", out firstInstance);
                if (firstInstance)
                    Application.Run(new Monitor());
                mutex.Close();
                mutex.Dispose();
            }
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="MutexMultiProcessFileAppender" /> class.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="parameters">The parameters.</param>
        public MutexMultiProcessFileAppender(string fileName, ICreateFileParameters parameters)
            : base(fileName, parameters)
        {
            try
            {
                mutex = new Mutex(false, GetMutexName(fileName));
                file = CreateFileStream(true);
            }
            catch
            {
                if (mutex != null)
                {
                    mutex.Close();
                    mutex = null;
                }

                if (file != null)
                {
                    file.Close();
                    file = null;
                }

                throw;
            }
        }
示例#26
0
        protected override void OnStartup(StartupEventArgs e)
        {
            //只允许运行一个实例
            bool createdNew = false;
            FileInfo file = new FileInfo(Assembly.GetExecutingAssembly().Location);

            Environment.CurrentDirectory = file.DirectoryName;

            GlobalDataSingleton.Instance.ExeFileLocation = file.FullName;
            mutex = new Mutex(true, "{ximalaya-thirdpart}", out createdNew);

            if (e.Args != null && e.Args.Length > 0)
            {
                WriteToMappedFile(e.Args[0]);
            }
            else
            {
                WriteToMappedFile(string.Empty);
            }

            if (!createdNew)
            {
                Debug.WriteLine("**********************************************************************");
                Debug.WriteLine("检测到已有一个喜马拉雅第三方客户端在运行,程序将关闭");
                Debug.WriteLine("**********************************************************************");
                Shutdown(0);
                return;
            }

            //设置调试输出
            Debug.AutoFlush = true;
            Debug.Listeners.Add(new TextWriterTraceListener("ximalaya.log"));

            Debug.WriteLine(string.Empty);
            Debug.WriteLine("**********************************************************************");
            Debug.WriteLine("喜马拉雅第三方客户端启动时间:" + DateTime.Now);
            Debug.WriteLine("**********************************************************************");
            Debug.WriteLine(string.Empty);

            Exit += new ExitEventHandler((sender, e1) =>
            {
                mutex.Close();
                mutex = null;
                Debug.WriteLine(DateTime.Now.ToShortDateString() + " 程序结束,返回代码为" + e1.ApplicationExitCode);
            });

            System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;

            /* 这句话可以使Global User Interface这个默认的组合字体按当前系统的区域信息选择合适的字形。
             * 只对FrameworkElement有效。对于FlowDocument,由于是从FrameworkContentElement继承,
             * 而且FrameworkContentElement.LanguageProperty.OverrideMetadata()无法再次执行,
             * 目前我知道的最好的办法是在使用了FlowDocument的XAML的根元素上加上xml:lang="zh-CN",
             * 这样就能强制Global User Interface在FlowDocument上使用大陆的字形。
             * */
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.Name)));

            base.OnStartup(e);
            new MyBootstrapper().Run();
        }
示例#27
0
        static void Main(string[] args)
        {
            if (args == null || args.Length <= 0)
            {
                return;
            }

            try
            {
                var isServerRunning = true;
                using (var mutex = new Mutex(false, mutexId))
                {
                    try
                    {
                        //ミューテックスの所有権を要求する
                        if (mutex.WaitOne(0, false))
                        {
                            //取得できた
                            isServerRunning = false;
                            mutex.ReleaseMutex();
                            mutex.Close();
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        //isServerRunning = false;
                    }
                }

                if (!isServerRunning)
                {
                    var dir = System.AppDomain.CurrentDomain.BaseDirectory;
                    var path = dir + serverPath;

                    var psi = new ProcessStartInfo() { FileName = path, WorkingDirectory = dir };

                    var p = System.Diagnostics.Process.Start(psi);
                }

                using (var pipeClient =
                    new NamedPipeClientStream(".", pipeId, PipeDirection.Out))
                {
                    pipeClient.Connect(10000);

                    // Read user input and send that to the client process.
                    using (var sw = new StreamWriter(pipeClient))
                    {
                        sw.AutoFlush = true;
                        foreach (var line in args)
                        {
                            sw.WriteLine(line);
                        }
                    }
                }
            }
            catch (NotImplementedException)//(Exception e)
            {
            }
        }
示例#28
0
 public static void closeMutex()
 {
     if (_appMutex != null)
     {
         _appMutex.Close();
         _appMutex = null;
     }
 }
示例#29
0
 private bool CheckAnotherInstance()
 {
     bool isFirst;
     System.Threading.Mutex mtx = new System.Threading.Mutex
                                                         (false, "zjdd ", out   isFirst);
     mtx.Close();
     return !isFirst;
 }
示例#30
0
        static void Main()
        {
            bool mutexCreated = false;
            Mutex mutex = new System.Threading.Mutex(true, @"Local\Surashu.SteamDeploy.exe", out mutexCreated);

            if (!mutexCreated)
            {
                mutex.Close();
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Main());

            mutex.Close();
        }
 public static void ReleaseMutex()
 {
     if (mutex != null)
     {
         mutex.ReleaseMutex();
         mutex.Close();
         mutex = null;
     }
 }
示例#32
0
        private bool CheckAnotherInstance()
        {
            bool isFirst;

            System.Threading.Mutex mtx = new System.Threading.Mutex
                                             (false, "zjdd ", out isFirst);
            mtx.Close();
            return(!isFirst);
        }
示例#33
0
 static void App()
 {
     mutex = new Mutex(false, "SINGLE_INSTANCE_MUTEX");
     if (!mutex.WaitOne(0, false))
     {
         mutex.Close();
         mutex = null;
     }
 }
示例#34
0
 public void ApplicationExit(object sender, ExitEventArgs e)
 {
     if (MUTEX != null)
     {
         MUTEX.Close();
         App.MUTEX = null;
     }
     RemoveTrayIcon();
 }
示例#35
0
        static void Main(string[] args)
        {
            var assem = System.Reflection.Assembly.GetExecutingAssembly();
            var attr  = (System.Runtime.InteropServices.GuidAttribute)Attribute.GetCustomAttribute(assem, typeof(System.Runtime.InteropServices.GuidAttribute));
            var guid  = attr.Value;

            System.Threading.Mutex mutex;
            bool hasHandle = false;

            using (mutex = new System.Threading.Mutex(false, guid)) {
                try {
                    try {
                        // Mutexの所有権を要求
                        hasHandle = mutex.WaitOne(0, false);
                    } catch (System.Threading.AbandonedMutexException) {
                        // 別アプリがMutexオブジェクトを開放しないで終了した場合
                        hasHandle = true;

                        //throw;
                    }
                    if (hasHandle == false)
                    {
                        // Mutexの所有権が得られなかったため、起動済みと判断して終了
                        MessageBox.Show("既に起動されています。");
                        return;
                    }

                    //---------------------------------------------------------
                    // アプリケーション開始
                    //---------------------------------------------------------
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    //AoedeGlobal _g = new AoedeGlobal();
                    AoedeStaticGlobal.Settings = AoEDEAlarmSettings.LoadXml();
                    StartHotkeys();
                    NotifyIcon ni = SetNotifyIcon();

                    System.Windows.Forms.Application.Run();

                    ni.Dispose();
                    AoEDEAlarmSettings.SaveXml(AoedeStaticGlobal.Settings);
                } catch (Exception ex) {
                    // アプリケーション例外処理
                    Console.WriteLine(ex.Message);

                    //throw;
                } finally {
                    if (hasHandle)
                    {
                        mutex.ReleaseMutex();
                    }
                    mutex.Close();
                }
            }
        }
 public static bool IsRegister(string name)
 {
     bool createdNew;
     Mutex mutex = new Mutex(true, name, out createdNew);
     if (createdNew)
     {
         mutex.Close();
     }
     return !createdNew;
 }
示例#37
0
		/// <summary>
		/// Acquires an exclusive lock on the properties file so that it can be opened safely.
		/// </summary>
		static IDisposable LockPropertyFile()
		{
			Mutex mutex = new Mutex(false, "PropertyServiceSave-30F32619-F92D-4BC0-BF49-AA18BF4AC313");
			mutex.WaitOne();
			return new CallbackOnDispose(
				delegate {
					mutex.ReleaseMutex();
					mutex.Close();
				});
		}
示例#38
0
 public static System.IDisposable LockPropertyFile()
 {
     System.Threading.Mutex mutex = new System.Threading.Mutex(false, "PropertyServiceSave-30F32619-F92D-4BC0-BF49-AA18BF4AC313");
     mutex.WaitOne();
     return(new CallbackOnDispose(delegate
     {
         mutex.ReleaseMutex();
         mutex.Close();
     }
                                  ));
 }
示例#39
0
文件: AchorRod.cs 项目: netHobby/Hi
        public FrmTrail()
        {
            InitializeComponent();

            //mutex = new Mutex(false, this.NameSpace + "_Single_MUTEX");
            Mutex = new Mutex(false,"_Single_MUTEX");
            if (!Mutex.WaitOne(0, false))
            {
                Mutex.Close();
                Mutex = null;
            }
        }
示例#40
0
        static void Main()
        {
            Process proc64    = null;
            Mutex   mutex     = new System.Threading.Mutex(false, mutexName);
            bool    hasHandle = false;

            try {
                //多重起動の抑止
                try {
                    hasHandle = mutex.WaitOne(0, false);
                } catch (AbandonedMutexException) {
                    hasHandle = true;
                }

                if (hasHandle == false)
                {
                    return;
                }

                //フック開始
                StartHook();

                //64bitプロセスの起動
                try {
                    proc64 = Process.Start("FF64.exe");
                } catch {
                    //まあいいや。
                }

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            } catch (Exception e) {
                MessageBox.Show(e.Message);
            } finally {
                try {
                    if (proc64 != null)
                    {
                        proc64.Kill();
                    }
                } catch {
                    //まあいいや。
                }

                EndHook();

                if (hasHandle)
                {
                    mutex.ReleaseMutex();
                }
                mutex.Close();
            }
        }
示例#41
0
        static void Main(string[] args)
        {
            Program p = new Program();

            string mutexName = "FileReminder";

            bool createdNew;

            System.Threading.Mutex mutex =
                new System.Threading.Mutex(true, mutexName, out createdNew);

            if (createdNew)
            {
                ChannelServices.RegisterChannel(new IpcServerChannel(Application.ProductName), true);

                RemotingServices.Marshal(p, "open");

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(f = new FileReminder());
            }
            else
            {
                mutex.Close();

                ChannelServices.RegisterChannel(new IpcClientChannel(), true);

                p = Activator.GetObject(typeof(Program), "ipc://" + Application.ProductName + "/open") as Program;

                if (p.StartupNextInstance(args))
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new FileReminder());
                }
            }

            mutex.Close();
        }
示例#42
0
        /// <summary>
        /// Cleans up single-instance code, clearing shared resources, mutexes, etc.
        /// </summary>
        public static void Cleanup()
        {
            if (OpenRPAMutex != null)
            {
                OpenRPAMutex.Close();
                OpenRPAMutex = null;
            }

            if (channel != null)
            {
                ChannelServices.UnregisterChannel(channel);
                channel = null;
            }
        }
示例#43
0
        static ApplicationProcess()
        {
            id = Environment.UserName + "@" + Uri.EscapeUriString(Assembly.GetEntryAssembly().Location.ToLower());
            mutex = new Mutex(false, id, out isStarted);
            isStarted = !isStarted;

            if(isStarted){
                controler = new Lazy<IRemoteControler>(() => GetRemoteControler());
                mutex.Close();
            }else{
                actions = new Dictionary<string, Delegate>();
                serverChannel = new Lazy<IChannel>(() => RegisterRemoteControler(typeof(RemoteControler)));
            }
        }
示例#44
0
        public void Run()
        {
            Console.WriteLine("Listening to mapped file " + Config.MAPPED_FILE_NAME);
            var mutexName = "mmfclientmutex" + (Guid.NewGuid());
            Console.Title = mutexName;

            var lastValidGuid = new Guid();

            while (true)
            {
                try
                {
                    using (var map = MemoryMappedFile.CreateOrOpen(Config.MAPPED_FILE_NAME, Config.BufferSize))
                    {
                        bool mutexCreated;
                        var mutex = new Mutex(true, mutexName, out mutexCreated);

                        using (var stream = map.CreateViewStream())
                        {
                            var timestamp = DateTime.Now;

                            var serializer = new BinaryFormatter();
                            AudioDataDTO result;

                            try {
                                result = serializer.Deserialize(stream) as AudioDataDTO;
                            } catch (SerializationException) {
                                continue;
                            }

                            if (result == null) continue;
                            if(result.Guid == lastValidGuid) continue;

                            var diff = timestamp - result.Timestamp;
                            lastValidGuid = result.Guid;

                            Console.WriteLine("Message in; delay: " + diff.TotalMilliseconds);
                            Console.WriteLine(result.ToString());
                        }
                        mutex.ReleaseMutex();
                        mutex.WaitOne();
                        mutex.Close();
                    }
                }
                catch (Exception ex) {
                    Console.WriteLine("Error: " + ex.Message);
                }
            }
        }
示例#45
0
        private static void RunMutex()
        {
            Mutex mutex = new System.Threading.Mutex(false, "JamCastMutex");

            try
            {
                bool tryAgain = true;
                while (tryAgain)
                {
                    bool result = false;
                    try
                    {
                        result = mutex.WaitOne(0, false);
                    }
                    catch (AbandonedMutexException ex)
                    {
                        // No action required
                        result = true;
                    }
                    if (result)
                    {
                        // Run the application
                        tryAgain = false;
                        Run();
                    }
                    else
                    {
                        foreach (Process proc in Process.GetProcesses())
                        {
                            if (proc.ProcessName.Equals(Process.GetCurrentProcess().ProcessName) && proc.Id != Process.GetCurrentProcess().Id)
                            {
                                proc.Kill();
                                break;
                            }
                        }
                        // Wait for process to close
                        Thread.Sleep(2000);
                    }
                }
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.Close();
                    mutex = null;
                }
            }
        }
 /// <summary>
 /// Provides a global access point for the single instance of the <see cref="DBConnectionStringProvider"/>
 /// class.
 /// </summary>
 /// <returns>A reference to the single instance of <see cref="DBConnectionStringProvider"/>.</returns>
 public static DBConnectionStringProvider Instance()
 {
     if (instance==null)
     {
         //Make sure the call is thread-safe.
         Mutex mutex=new Mutex();
         mutex.WaitOne();
         if( instance == null )
         {
             instance = new DBConnectionStringProvider();
         }
         mutex.Close();
     }
     return instance;
 }
 /// <summary>
 /// Provides a global access point for the single instance of the <see cref="GlobalSettingsProvider"/>
 /// class.
 /// </summary>
 /// <returns>A reference to the single instance of <see cref="GlobalSettingsProvider"/>.</returns>
 public static GlobalSettingsProvider Instance()
 {
     if (instance==null)
     {
         //Make sure the call is thread-safe.
         Mutex mutex=new Mutex();
         mutex.WaitOne();
         if( instance == null )
         {
             instance = new GlobalSettingsProvider();
         }
         mutex.Close();
     }
     return instance;
 }
示例#48
0
 /// <summary>
 /// Provides a global access point for the single instance of the <see cref="BannedHostsCache"/>
 /// class.
 /// </summary>
 /// <returns>A reference to the single instance of <see cref="BannedHostsCache"/>.</returns>
 public static BannedHostsCache Instance()
 {
     if (instance==null)
     {
         //Make sure the call is thread-safe.
         Mutex mutex=new Mutex();
         mutex.WaitOne();
         if( instance == null )
         {
             instance = new BannedHostsCache();
         }
         mutex.Close();
     }
     return instance;
 }
示例#49
0
        static void Main()
        {
            /// 多重起動禁止判定 Start ///
            //Mutex名を決める(必ずアプリケーション固有の文字列に変更すること
            string muteName = "SweatingApp";

            bool createdNew;

            System.Threading.Mutex mutex = new System.Threading.Mutex(true, muteName, out createdNew);

            //ミューテックスの初期所有権が付与されたか調べる
            if (createdNew == false)
            {
                //されていなかった場合、既に起動していると判断して終了
                MessageBox.Show("既にこのアプリ起動されています。", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                mutex.Close();
                return;
            }
            /// 多重起動禁止判定 End ///


            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

            try
            {
                //常駐アプリを作成する場合
                Resident resident = new Resident();
                Application.Run();
            }
            finally
            {
                //ミューテックスを解放する。
                mutex.ReleaseMutex();
                mutex.Close();
            }
        }
示例#50
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // BETA/CTP code
            //if (DateTime.Today > new DateTime(2012, 2, 28))
            //{
            //    MessageBox.Show("This TEST version has expired. Please visit http://proxyswitcher.net for a newer version.", "Proxy Switcher", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            //    Application.Current.Shutdown(600);
            //    return;
            //}

            try
            {
                string versionGuid = "35B89795-EA7A-4098-90B7-1B88EF5F50FF";
                string mutexName = @"Global\ProxySwitcher" + versionGuid;

                bool firstInstance;

                mutex = new Mutex(true, mutexName, out firstInstance);

                Logger.Log("IsFirstInstance: " + firstInstance.ToString());

                if (!firstInstance)
                {
                    CallRunningInstance(e.Args);
                    Application.Current.Shutdown();
                    return;
                }

                try
                {
                    InitRemoting();
                }
                catch (Exception remoteEx)
                {
                    Logger.Log("Initializing remoting failed. Calls from Windows 7 Superbar Jumplist and from a command line will not work correctly.", remoteEx);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An unhandled exception during startup has occured. Please send a bug report to [email protected] with the following details:" + Environment.NewLine + Environment.NewLine + ex.Message + Environment.NewLine + Environment.NewLine + "More details can be found in Log.txt in " + SettingsManager.GetSettingsFolder(), "Error", MessageBoxButton.OK, MessageBoxImage.Stop);
                Logger.Log("Unhandled Startup Exception: " + ex.Message, ex);

                if (mutex != null)
                    mutex.Close();

                Application.Current.Shutdown(700);
            }
        }
示例#51
0
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ps.running = false;
            PipeServer.SendPipeMessgae("exit|exit|exit");

            Settings.Settings.Default.autoSave = (bool)autoSelect.IsChecked;
            if (null != thDownload)
            {
                thDownload.Abort();
            }
            if (null != thSearch)
            {
                thSearch.Abort();
            }
            mtx.Close();
        }
        /// <summary>
        /// Cleans up single-instance code, clearing shared resources, mutexes, etc.
        /// </summary>
        public static void Cleanup()
        {
            if (stopWaitingPipeConnectionTokenSource != null)
            {
                stopWaitingPipeConnectionTokenSource.Cancel();
            }

            if (singleInstanceMutex != null)
            {
                singleInstanceMutex.Close();
                singleInstanceMutex = null;
            }

            if (pipeServer != null)
            {
                pipeServer.Close();
                pipeServer = null;
            }
        }
示例#53
0
        public static void InitiateCommand()
        {
            var t = new Thread(() => {
                Mutex mutex = new System.Threading.Mutex(false, "lspdbg_instance");
                try {
                    if (mutex.WaitOne(0, false) || MessageBox.Show("An instance of Lisp Debugging Assistant is already running.\nMake sure to check on the tray icons.\nWould you still like to open a new instance?", "Instance Already Exists", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
                    {
                        SystemSounds.Asterisk.Play();
                        Application.Run(Main.MainForm = new MainForm());
                    }
                } finally {
                    mutex?.Close();
                }
            });

            t.SetApartmentState(ApartmentState.STA);
            t.IsBackground = true;
            t.Start();
        }
示例#54
0
        static void Main()
        {
            // © DOBON!.
            //Mutex関係
            // https://dobon.net/vb/dotnet/process/checkprevinstance.html
            //Mutex名を決める(必ずアプリケーション固有の文字列に変更すること!)
            string mutexName = "MABProcess";

            //Mutexオブジェクトを作成する
            System.Threading.Mutex mutex = new System.Threading.Mutex(false, mutexName);

            bool hasHandle = false;

            try {
                try {
                    hasHandle = mutex.WaitOne(0, false);
                }
                //.NET Framework 2.0以降の場合
                catch (System.Threading.AbandonedMutexException) {
                    hasHandle = true;
                }
                if (hasHandle == false)
                {
                    return;
                }

                new AppConfig();
                Config.Load();
                Util.NotReadonly(AppConfig.BackupPath);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Form1 f = new Form1();
                Application.Run();
            }
            finally {
                if (hasHandle)
                {
                    mutex.ReleaseMutex();
                }
                mutex.Close();
            }
        }
示例#55
0
        static void Main()
        {
            Mutex mutex = new System.Threading.Mutex(false, "WorkFlowMenagement");

            try
            {
                if (mutex.WaitOne(0, false))
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    //Application.Run(new ItineraryPlaneSeries());
                    string serevr = "SERVER";
                    //string serevr = "SERVER";
                    string newserv = "Data Source=" + serevr + ";Initial Catalog=NelnaDB;Integrated Security=True";
                    if (Properties.Settings.Default.NewConStr == newserv)
                    {
                        #region
                        Application.Run(new Splash());
                        // After splash form closed, start the main form.
                        Application.Run(new LoginWindow());
                        #endregion
                    }
                    else
                    {
                        #region
                        Application.Run(new ProvideConstrForm());
                        //Application.Run(new Splash());
                        #endregion
                    }
                }
                else
                {
                    MessageBox.Show("An instance of the application is already running.", "Application Exsist", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally { if (mutex != null)
                      {
                          mutex.Close(); mutex = null;
                      }
            }
        }
示例#56
0
        static void Main()
        {
            Mutex appSingleInstance = new System.Threading.Mutex(false, "SingleInstanceApp#@145");

            if (appSingleInstance.WaitOne(0, false))
            {
                try
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Frm_Main());
                    appSingleInstance.Close();
                }
                catch (Exception ex)
                {
                    Client.Components.Classes.Log objLog = new Components.Classes.Log();
                    objLog.WriteFile(ex.Message.ToString() + "\r\n" + ex.StackTrace);
                    Application.Exit();
                    //MessageBox.Show(ex.ToString());
                }
            }
        }
示例#57
0
        static void Main(string[] args)
        {
            string selfLocation = System.Reflection.Assembly.GetEntryAssembly().Location;
            string alterfulPath = Path.GetDirectoryName(selfLocation) + @"\Alterful.exe";

            // No arg: just startup alterful
            if (args.Count() != 1)
            {
                StartAlterful(alterfulPath, ""); return;
            }

            // One arg: add as alterful startup item
            targetPath = args[0].Trim();
            if (!System.IO.File.Exists(targetPath) && !System.IO.Directory.Exists(targetPath))
            {
                return;
            }

            // Is alterful running
            bool flag = false;

            System.Threading.Mutex mutex = new System.Threading.Mutex(true, "Alterful", out flag);
            if (!flag) // running
            {
                Thread pipeThread = new Thread(new ThreadStart(SendData));
                pipeThread.IsBackground = true;
                pipeThread.Start();
                Thread.Sleep(251);
            }
            else // not running
            {
                mutex.Close();

                // Start alterful
                StartAlterful(alterfulPath, targetPath);
                Thread.Sleep(996);
            }
        }
        static void Main(string[] args)
        {
            const string mutexName = "RUNMEONLYONCE";

            System.Threading.Mutex mutex = null;
            while (true)
            {
                try
                {
                    mutex = Mutex.OpenExisting(mutexName);
                    Console.WriteLine("Mutex found, exiting..");
                    mutex.Close();
                    break;
                }
                catch (WaitHandleCannotBeOpenedException)
                {
                    bool mutexIsMine = true;
                    mutex = new Mutex(mutexIsMine, mutexName);
                    Console.WriteLine("Mutex not found, created.");
                }
            }
            Console.ReadKey();
        }
示例#59
0
        static void Main()
        {
            Mutex mutex = new System.Threading.Mutex(false, "RisemUSBMutexKeyThisIsAPrivateSecret");

            try
            {
                if (mutex.WaitOne(0, false))
                {
                    // Run the application
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new RisemUSB());
                }
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.Close();
                    mutex = null;
                }
            }
        }
示例#60
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="counterId"></param>
        /// <param name="registryId"></param>
        /// <param name="rfId"></param>
        /// <param name="userInfo"></param>
        /// <param name="role"></param>
        /// <returns></returns>
        public static void GeneratePrintRepertorio(String counterId, String registryId, String rfId, InfoUtente userInfo, Ruolo role)
        {
            System.Threading.Mutex mutex   = null;
            StampaRepertorio       printer = new StampaRepertorio();

            try
            {
                // Creazione o reperimento del mutex
                mutex = CreateMutex(counterId);
                mutex.WaitOne();
                printer.GeneratePrintRepertorio(counterId, registryId, rfId, userInfo, role);
            }
            finally
            {
                //Rilascio il mutex
                if (mutex != null)
                {
                    mutex.ReleaseMutex();
                    mutex.Close();
                    mutex = null;
                }
            }
        }