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; } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //DevExpress.Skins.SkinManager.EnableFormSkins(); //UserLookAndFeel.Default.SetSkinStyle("Office 2013"); CurrentUser=new User(); // Giá trị luận lý cho biết ứng dụng này // có quyền sở hữu Mutex hay không. bool ownmutex; // Tạo và lấy quyền sở hữu một Mutex có tên là Icon; using (var mutex = new Mutex(true, "Icon", out ownmutex)) { // Nếu ứng dụng sở hữu Mutex, nó có thể tiếp tục thực thi; // nếu không, ứng dụng sẽ thoát. if (ownmutex) { Application.Run(new FormLogin()); //giai phong Mutex; mutex.ReleaseMutex(); } else Application.Exit(); } }
public static Mutex AcquireMutex(NodeUri nodeUri, TimeSpan timeout) { Debug.Print("Acquire Mutex for Node URI '{0}'", nodeUri); var mutexName = GetMutexName(nodeUri); Debug.Print("Acquire Mutex name: '{0}'", mutexName); bool mutexCreated; var mutex = new Mutex(false, mutexName, out mutexCreated); Debug.Print("Mutex instance resolved - instance created: {0}", mutexCreated); try { Debug.Print("Try to aquire lock on mutex using timeout {0}", timeout); if (!mutex.WaitOne(timeout)) { throw new TimeoutException(string.Format("Cannot acquire Mutex for URI '{0}' - there is another Node already exists for the same URI", nodeUri)); } Debug.Print("Mutex successfully acquired!"); return mutex; } catch (AbandonedMutexException abandonedMutexException) { Debug.Print("Mutex Abandoned Exception: {0}", abandonedMutexException.Message); mutex.ReleaseMutex(); return AcquireMutex(nodeUri, timeout); } }
static void Main() { Util.Utils.ReleaseMemory(); using (Mutex mutex = new Mutex(false, "Global\\" + "71981632-A427-497F-AB91-241CD227EC1F")) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (!mutex.WaitOne(0, false)) { Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks"); if (oldProcesses.Length > 0) { Process oldProcess = oldProcesses[0]; } MessageBox.Show("Shadowsocks is already running.\n\nFind Shadowsocks icon in your notify tray."); return; } Directory.SetCurrentDirectory(Application.StartupPath); #if !DEBUG Logging.OpenLogFile(); #endif ShadowsocksController controller = new ShadowsocksController(); MenuViewController viewController = new MenuViewController(controller); controller.Start(); Application.Run(); } }
protected override void OnStartup(StartupEventArgs e) { // store mutex result bool createdNew; // allow multiple users to run it, but only one per user var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); // create mutex _instanceMutex = new Mutex(true, @"Global\MercurialForge_Mastery", out createdNew, securitySettings); // check if conflict if (!createdNew) { MessageBox.Show("Instance of Mastery is already running"); _instanceMutex = null; Application.Current.Shutdown(); return; } base.OnStartup(e); MainWindow window = new MainWindow(); MainWindowViewModel viewModel = new MainWindowViewModel(window); window.DataContext = viewModel; window.Show(); }
static void Main() { bool instantiated = false; // Local means in per-session namespace; alternative is Global string mutexName = "Local\\" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; Mutex mutex = new Mutex (false, mutexName, out instantiated); if (instantiated) { // If instantiated is true, this is the first instance // of the application; else, another instance is running. Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TriagePic()); } else { MessageBox.Show("Sorry, only one instance of TriagePic can run at a time."); // If instead we wanted to quietly use the existing instance, could move focus to it: // Process current = Process.GetCurrentProcess(); // foreach (Process process in Process.GetProcessesByName(current.ProcessName)) // { // if (process.Id != current.Id) // { // SetForegroundWindow(process.MainWindowHandle); // break; // } // } Application.Exit(); } GC.KeepAlive(mutex); // Needed since mutex itself isn't static }
static void Main() { bool createdNew; //是否是第一次开启程序 Mutex mutex = new Mutex(false, "Single", out createdNew);//实例化一个进程互斥变量,标记名称Single if (!createdNew) //如果多次开启了进程 { Process currentProcess = Process.GetCurrentProcess();//获取当前进程 foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName)) { //通过进程ID和程序路径来获取一个已经开启的进程 if ((process.Id != currentProcess.Id) && (Assembly.GetExecutingAssembly().Location == process.MainModule.FileName)) { //获取已经开启的进程的主窗体句柄 IntPtr mainFormHandle = process.MainWindowHandle; if (mainFormHandle != IntPtr.Zero) { ShowWindowAsync(mainFormHandle, 1); //显示已经开启的进程窗口 SetForegroundWindow(mainFormHandle); //将已经开启的进程窗口移动到窗体的最前端 } } } MessageBox.Show("进程已经开启"); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormSingleProcess()); }
static void Main(string[] args) { bool can_execute = true; try { mutex = new System.Threading.Mutex(false, "MONITORMANAGER", out can_execute); } catch (Exception ex) { _logService.Error("ExistCatch:获取Mutex时出现异常:" + ex.ToString()); } if (can_execute) { Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += Application_ThreadException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (args == null || args.Length == 0 || args[0].ToLower() == "true") { Application.Run(new MonitorMain(true)); } else { Application.Run(new MonitorMain(false)); } } else { _logService.Info("MONITORMANAGER already running!"); Debug.WriteLine("MONITORMANAGER already running!"); } }
static void Main() { bool createdNew = true; using (Mutex mutex = new Mutex(true, "Math Monkeys", out createdNew)) { if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); MMControl programController = new MMControl(); programController.RunProgram(); //Application.Run(new frmLogin()); } else { MessageBox.Show("Math Monkeys is already running.", "Math Monkeys", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } #region Test Code /* XmlDocument xd = new XmlDocument(); xd.Load(@"\t.xml"); // Console.WriteLine(xd.SelectSingleNode("Test/testitem/name").InnerText); //Console.ReadKey(); * */ #endregion }
public SensorForm(MainForm mainForm) { _mf = mainForm; dispMutex = new Mutex(); InitializeComponent(); waveBoxV.Initialize(10,10,-10); _lineName.Add((int)DataType.Heading, "艏向角"); _lineName.Add((int)DataType.Pitch, "纵倾"); _lineName.Add((int)DataType.Roll, "横摇"); _lineName.Add((int)DataType.Pressure, "压强"); _lineName.Add((int)DataType.Temperature, "温度"); _lineName.Add((int)DataType.Speed, "航速"); _lineName.Add((int)DataType.Depth, "拖体深度"); _lineName.Add((int)DataType.Altitude, "底深"); MonoColors.Add(Color.Aqua); MonoColors.Add(Color.Blue); MonoColors.Add(Color.BlueViolet); MonoColors.Add(Color.Brown); MonoColors.Add(Color.BurlyWood); MonoColors.Add(Color.CadetBlue); MonoColors.Add(Color.Chartreuse); MonoColors.Add(Color.Chocolate); MonoColors.Add(Color.CornflowerBlue); MonoColors.Add(Color.Crimson); MonoColors.Add(Color.DeepPink); waveBoxV.AddLine(_lineName[(int)DataType.Heading], MonoColors[0]); waveBoxV.AddLine(_lineName[(int)DataType.Pitch], MonoColors[1]); waveBoxV.AddLine(_lineName[(int)DataType.Roll], MonoColors[2]); option.bShowHeading = true; option.bShowPitch = true; option.bShowRoll = true; }
private void fmMain_Load(object sender, EventArgs e) { bool r; AppMutex = new Mutex(true, "AndonSys.AppHelper", out r); if (!r) { MessageBox.Show("系统已运行!",this.Text); Close(); return; } CONFIG.Load(); log = new Log(Application.StartupPath, "AppHelper", Log.DEBUG_LEVEL); log.Debug("系统运行"); gdApp.AutoGenerateColumns = false; LoadApp(); tbApp.Show(); timer.Enabled = true; }
private Mutex mutex = null; // синхронизатор #endregion Fields #region Constructors public ChannelsViewForm(Application _app) { app = _app; InitializeComponent(); mutex = new Mutex(); }
static void Main() { #if !DEBUG bool ok; Mutex mutex = new Mutex(true, "XRefreshMutex", out ok); if (!ok) { MessageBox.Show("Another instance of XRefresh is already running. See icons in tray-bar.", "Multiple instances", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } #endif ResetWorkingDirectory(); Utils.DisableErrorReporting(Path.GetFileName(Application.ExecutablePath)); SetupExceptionsHandler(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // instead of running a form, we run an ApplicationContext Application.Run(new Context()); #if !DEBUG GC.KeepAlive(mutex); // important! #endif }
static void Main() { mutex = new Mutex(true, Process.GetCurrentProcess().ProcessName, out created); if (created) { //Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //Application.ThreadException += Application_ThreadException; //AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // As all first run initialization is done in the main project, // we need to make sure the user does not start a different knot first. if (CfgFile.Get("FirstRun") != "0") { try { ProcessStartInfo process = new ProcessStartInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\FreemiumUtilities.exe"); Process.Start(process); } catch (Exception) { } Application.Exit(); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); } }
static void Main() { bool createdMutex; var updateCheck = new UpdateCheck(); updateCheck.CheckUri = "http://minecraft.etherealwake.com/updates.xml"; updateCheck.Start(); using (var mutex = new Mutex(true, mutexName, out createdMutex)) { if (createdMutex) { // Created the mutex, so we are the first instance Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var mainform = new MainForm(); Application.Run(mainform); GC.KeepAlive(mutex); } else { // Not the first instance, so send a signal to wake up the other try { var message = NativeMethods.RegisterWindowMessage(mutexName); if (message != 0) { NativeMethods.PostMessage(NativeMethods.HWND_BROADCAST, message, IntPtr.Zero, IntPtr.Zero); } } catch { // We really don't care, we're quitting anyway } } } }
/// <summary> Creates and locks the named mutex or throws TimeoutException </summary> /// <exception cref="System.TimeoutException"> Raises System.TimeoutException if mutex was not obtained. </exception> public MutexLock(int timeout, string name) { _mutex = new Mutex(true, name, out _wasNew); _locked = _wasNew; _disposeMutex = true; Lock(timeout, ref _wasAbandonded); }
/// <summary> Locks the provided mutex or throws TimeoutException </summary> /// <exception cref="System.TimeoutException"> Raises System.TimeoutException if mutex was not obtained. </exception> public MutexLock(int timeout, Mutex mutex) { _wasNew = false; _mutex = Check.NotNull(mutex); _disposeMutex = false; Lock(timeout, ref _wasAbandonded); }
static void Main() { bool createdNew = true; using (Mutex mutex = new Mutex(true, "Global\\RPKeySender", out createdNew)) { if (createdNew) { // Start app - create new window Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { Application.Run(new Form1()); } catch (Exception ex) { try { Functions.WriteLineToLogFile("Top level exception:"); Functions.WriteExceptionToLogFile(ex); } catch { } } } else { MessageBox.Show("The Remote Potato IR Sender App is already running.\r\nDouble click the icon in the System Tray to open it."); } } }
static void Main() { Util.Utils.ReleaseMemory(); using (Mutex mutex = new Mutex(false, "Global\\ShadowsocksR_" + Application.StartupPath.GetHashCode())) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (!mutex.WaitOne(0, false)) { MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + "\n" + I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."), I18N.GetString("ShadowsocksR is already running.")); return; } Directory.SetCurrentDirectory(Application.StartupPath); //#if !DEBUG Logging.OpenLogFile(); //#endif ShadowsocksController controller = new ShadowsocksController(); MenuViewController viewController = new MenuViewController(controller); controller.Start(); Application.Run(); } }
static void Main(string[] args) { Process instance = RunningInstance(); if (instance != null) { HandleRunningInstance(instance); return; } else { bool canCreateThread; Mutex mutex = new Mutex(true, Application.UserAppDataPath.Replace("\\", "_"), out canCreateThread); if (!canCreateThread) { MessageBox.Show("应用程序已在运行中!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (args.Length > 0) { try { //string[] strTemp = args[0].Split('@'); //Common.globalAppVNo = strTemp[0]; //Common.globalAppMD5No = strTemp[1]; Common.globalUpdateList = args[0]; } catch { } } Application.Run(new UpdateForm()); } }
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(); } }
public static ReservedPort Reserve() { var port = 50000; while (port < ushort.MaxValue) { port++; if (!IsPortFree(port)) { continue; } bool createdNew; Mutex mutex = new Mutex(false, $@"Global\Knapcode.TorSharp.Tests.ReservedPort-{port}", out createdNew); lock (Lock) { if (ReservedPorts.Contains(port)) { continue; } var acquired = mutex.WaitOne(0, false); if (acquired) { ReservedPorts.Add(port); return new ReservedPort(port, mutex); } } } return null; }
private static void Main(string[] args) { Mutex mutex = new Mutex(true, AppDomain.CurrentDomain.BaseDirectory.Replace('\\', '_')); if (mutex.WaitOne(100)) { Logger.Instance.WriteMessage("Notifier started."); SkypeNotifier.Instance.StartTimer(); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); Application.Run(new Settings()); SkypeNotifier.Instance.StopTimer(); Logger.Instance.WriteMessage("Notifier halted."); } else { try { Process[] allProcesses = Process.GetProcessesByName("SkypeNotifier"); if (allProcesses.Length > 0) { Win32.SetForegroundWindow(allProcesses[0].MainWindowHandle); } return; } catch { } } mutex.ReleaseMutex(); }
public MutexLock(string mutexname) { m = new Mutex(false, mutexname); if(m.WaitOne(0, false) == false) { throw new MutexAlreadyExists(); } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var c = Process.GetCurrentProcess(); bool instance; var mutex = new Mutex(true, c.ProcessName + Application.ProductName, out instance); if (!instance) { // Search for instances of this application var first = false; foreach (var p in Process.GetProcessesByName(c.ProcessName).Where(p => p.Id != c.Id)) if (!first) { first = true; ShowWindow(p.MainWindowHandle, 5); SetForegroundWindow(p.MainWindowHandle); } else p.Kill(); } else { Application.Run(new FormMain()); GC.KeepAlive(mutex); } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // We make sure that no other instances of that application is not running. bool mutexIsAvailable; Mutex m = null; try { m = new Mutex(true, "Singleton"); // We are waiting for 1 ms. mutexIsAvailable = m.WaitOne(1, false); } catch (AbandonedMutexException) { // Do not worry about AbandonedMutexException. // Mutex only "protects" the application of it's copies. mutexIsAvailable = true; } if (!mutexIsAvailable) return; try { Application.Run(new Control()); } finally { m?.ReleaseMutex(); } }
public OSClient(IEFMagLinkRepository repository) { // First we set up our mutex and semaphore mutex = new Mutex(); connected = false; _repository = repository; item = new SocketAsyncEventArgs(); _timerClient.Elapsed += new System.Timers.ElapsedEventHandler(_timerClient_Elapsed); _timerClient.Interval = 10000; _timerClient.Start(); _timerClientConnecTimer.Elapsed += new System.Timers.ElapsedEventHandler(_timerClientConnecTimer_Elapsed); _timerClientConnecTimer.Interval = 15000; _timerClientConnecTimer.Start(); numconnections = 0; item.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted); item.SetBuffer(new Byte[Convert.ToInt32(Settings._instance.BufferSize)], 0, Convert.ToInt32(Settings._instance.BufferSize)); socketpool = new OSAsyncEventStack(Convert.ToInt32(Settings._instance.NumConnect)); for (Int32 i = 0; i < Convert.ToInt32(Settings._instance.NumConnect); i++) { SocketAsyncEventArgs item1 = new SocketAsyncEventArgs(); item1.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted); item1.SetBuffer(new Byte[Convert.ToInt32(Settings._instance.BufferSize)], 0, Convert.ToInt32(Settings._instance.BufferSize)); socketpool.Push(item1); } }
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(); } }
static void Main() { m = new System.Threading.Mutex(true, Application.ProductName + Application.ProductVersion, out Unica); if (!Unica) // Nos aseguramos que sea la única instancia de la aplicación. { MessageBox.Show("El programa ya se está ejecutando.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (AppConfig.SavedCredentials) { Application.Run(new frmMain()); } else { frmLogIn fl = new frmLogIn(); if (fl.ShowDialog() == DialogResult.Yes) { Application.Run(new frmMain(fl.TP)); } //TODO: Que pasa cuando DialogResult es distinto de Yes? } } GC.KeepAlive(m); }
static void Main() { // Создаём новый мьютекс на время работы программы... using (Mutex Mtx = new Mutex(false, Properties.Resources.AppName)) { // Пробуем занять и заблокировать, тем самым проверяя запущена ли ещё одна копия программы или нет... if (Mtx.WaitOne(0, false)) { // Включаем визуальные стили... Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Получаем переданные параметры командной строки... string[] CMDLineA = Environment.GetCommandLineArgs(); // Обрабатываем полученные параметры командной строки... if (CMDLineA.Length > 2) { if (CMDLineA[1] == "/lang") { try { Thread.CurrentThread.CurrentUICulture = new CultureInfo(CMDLineA[2]); } catch { MessageBox.Show(Properties.Resources.AppUnsupportedLanguage, Properties.Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } // Запускаем главную форму... Application.Run(new FrmMainW()); } else { // Программа уже запущена. Выводим сообщение об этом... MessageBox.Show(Properties.Resources.AppAlrLaunched, Properties.Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Information); // Завершаем работу приложения с кодом 16... Environment.Exit(16); } } }
static void Main() { bool OK; string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); Mutex mutex = new System.Threading.Mutex(true, appGuid, out OK); if (!OK) { MessageBox.Show("Vagrant Manager 的另一个实例已经在运行"); return; } App app = App.Instance; app.Run(); GC.KeepAlive(mutex); }
static void Main() { bool result; var mutex = new System.Threading.Mutex(true, "UniqueAppId", out result); if (!result) { MessageBox.Show("Sorry, only one instance of 7thHeaven can be run at a time! Please first close all instances of 7thHeaven if you are trying to import an IRO."); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.Run(new fLibrary()); GC.KeepAlive(mutex); }
/// <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; } }
static void Main() { bool instantiated; s_mutex = new System.Threading.Mutex(false, "Binglong.My.Application.Mutex", out instantiated); if (instantiated) { //Forcing the culture to English, this way we can read exceptions better from foreign users. Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-us"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { System.Windows.Forms.MessageBox.Show("MadCow is already open."); } }
static void Main() { /*if (PriorProcess() != null) * { * Application.Exit(); * //MessageBox.Show("You can run only 1 instance at a time!"); * return; * }*/ bool instantiated; systemMutex = new System.Threading.Mutex(false, "Popcorn-GDrive", out instantiated); if (instantiated) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new mainForm()); } }
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(); }
static void Main() { Application.ThreadException += Application_ThreadException; var mutex = new System.Threading.Mutex(false, Application.ExecutablePath.Replace('\\', '/')); if (!mutex.WaitOne(0, false)) { // 多重起動禁止 MessageBox.Show("既に起動しています。\r\n多重起動はできません。", "七四式電子観測儀", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); mutex.ReleaseMutex(); }
protected override void OnStop() { CDRLogger.Logger.LogInfo("OnStop()"); if (receiveIndex != null) { receiveIndex.Stop(); receiveIndex = null; } CDRLogger.Logger.LogInfo("KillAccountingThread();"); KillAccountingThread(); Webservice.ForceServiceOffline = true; // stop service code goes here base.OnStop(); CDRLogger.Logger.LogInfo("serviceMutex.ReleaseMutex();"); if (serviceMutex != null) { if (serviceMutex.WaitOne(TimeSpan.Zero, true)) { serviceMutex.ReleaseMutex(); serviceMutex = null; } } if (hostHealthService != null && hostHealthService.State == CommunicationState.Opened) { hostHealthService.Close(new TimeSpan(0, 0, 10)); // sluiten na max 10 seconden } if (host != null && host.State == CommunicationState.Opened) { host.Close(new TimeSpan(0, 0, 10)); // sluiten na max 10 seconden } CDRLogger.Logger.LogInfo("SMTPLogging.Close();"); SMTPLogging.Close(); CDRLogger.Logger.LogInfo("LogUsage.Close();"); LogUsage.Close(); }
static void Main(string[] args) { if (args.Length == 1 && (args[0] == "-help" || args[0] == "-h" || args[0] == "-?")) { MessageBox.Show(Configuration.HelpInfo); } else if (args.Length > 0 && !Configuration.CheckParam(args)) { MessageBox.Show("Incorrect parameters\n" + Configuration.HelpInfo); } #if !DEBUG bool newMutex; Mutex m = new System.Threading.Mutex(true, @"Global\" + Application.ProductName, out newMutex); { if (newMutex) { #endif Configuration config = null; Form frmMain = null; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (args.Length > 0 && Configuration.CheckParam(args)) { config = Configuration.Configure(args); frmMain = new Frm_Main(config); } else { frmMain = new Frm_Main(); } Application.Run(frmMain); #if !DEBUG } else { MessageBox.Show("程序已运行。"); } } #endif }
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(); } }
void App_Startup(object sender, StartupEventArgs e) { bool ret; mutex = new System.Threading.Mutex(true, "StarsectorLTool", out ret); if (!ret) { MessageBox.Show("已有一个程序运行"); Environment.Exit(0); } var process = Process.GetProcessesByName("sslt_autoUpdate"); if (process != null && process.Length > 0) { Environment.Exit(0); } //Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); }
protected override void OnStartup(StartupEventArgs e) { _mutex = new Mutex(true, "C2DHaceel", out bool createdNew); if (!createdNew) { Application.Current.Shutdown(); } else { Exit += CloseMutexHandler; } base.OnStartup(e); _notifyIcon.Click += (s, args) => ShowMainWindow(); _notifyIcon.Icon = C2D.Properties.Resources.AppIcon; _notifyIcon.Visible = true; CreateContextMenu(); }
static void Main() { bool res = false; System.Threading.Mutex mutex = new System.Threading.Mutex(true, "SuarTool", out res); if (res) { CultureInfo cu = new CultureInfo("ar"); Thread.CurrentThread.CurrentCulture = cu; Thread.CurrentThread.CurrentUICulture = cu; CultureInfo.DefaultThreadCurrentCulture = cu; CultureInfo.DefaultThreadCurrentUICulture = cu; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FrmTray()); } }
protected override void OnStartup(StartupEventArgs startupEvent) { string mutexId = ((System.Runtime.InteropServices.GuidAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false).GetValue(0)).Value.ToString(); _mutex = new System.Threading.Mutex(true, mutexId, out bool createdNew); if (!createdNew) { Current.Shutdown(); } else { Exit += CloseMutexHandler; } base.OnStartup(startupEvent); SetupDebugLogging(); SetupLoggingForProcessWideEvents(); base.OnStartup(startupEvent); _log.Debug($"adrilight {VersionNumber}: Main() started."); kernel = SetupDependencyInjection(false); this.Resources["Locator"] = new ViewModelLocator(kernel); UserSettings = kernel.Get <IUserSettings>(); _telemetryClient = kernel.Get <TelemetryClient>(); SetupNotifyIcon(); if (!UserSettings.StartMinimized) { OpenSettingsWindow(); } kernel.Get <AdrilightUpdater>().StartThread(); SetupTrackingForProcessWideEvents(_telemetryClient); }
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; } } }
/// <summary> /// Checks if the instance of the application attempting to start is the first instance. /// If not, activates the first instance. /// </summary> /// <returns>True if this is the first instance of the application.</returns> public static bool InitializeAsFirstInstance(string uniqueName) { var commandLineArgs = Environment.GetCommandLineArgs(); // Build unique application Id and the channel name. string applicationIdentifier = uniqueName + Environment.UserName; string channelName = String.Concat(applicationIdentifier, ":", "SingeInstanceChannel"); singleInstanceMutex = new Mutex(true, applicationIdentifier, out var isSingleInstance); if (isSingleInstance) { CreateRemoteService(channelName); } else { SignalFirstInstance(channelName, commandLineArgs); } return(isSingleInstance); }
public static void ReStart(bool hasOther = false) { if (!hasOther) { App.MUTEX?.Close(); App.MUTEX = null; } Task.Delay(2000).ContinueWith(t => { App.Current.Dispatcher.Invoke(new Action(() => { (App.Current as App).ApplicationExit(null, null); SDKClient.SDKClient.Instance.StopAsync().ConfigureAwait(false); Application.Current?.Shutdown(0); string mainProgramPath = string.Format(@"{0}\IMUI.exe", AppDomain.CurrentDomain.BaseDirectory); System.Diagnostics.Process.Start(mainProgramPath); })); }); }
static void Main() { bool flagMutex; System.Threading.Mutex m_hMutex = new System.Threading.Mutex(true, "Pheonix_Launcher", out flagMutex); if (flagMutex) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // 실행할 Form 클래스 Application.Run(new Form1()); m_hMutex.ReleaseMutex(); } else { // 여러개 실행시켰을때 띄울 메시지 MessageBox.Show("프로그램이 이미 실행 중입니다", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
static void Main() { bool createNew; using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out createNew)) { if (createNew) { //Application.ThreadException += new ThreadExceptionEventHandler(UIThreadException); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); DevExpress.Data.CurrencyDataController.DisableThreadingProblemsDetection = true; Application.Run(new frmMain()); } else { System.Threading.Thread.Sleep(1000); System.Environment.Exit(1); } } }
static void Main() { //处理非UI线程异常 Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); mutex = new System.Threading.Mutex(true); if (mutex.WaitOne(0, false)) { //处理未捕获的异常 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //处理UI线程异常 Application.ThreadException += Application_ThreadException; Application.Run(new TransferDBMainForm()); } else { Application.Exit(); } }
public override void _Ready() { players = new List <Character>(); entityBindings = new Dictionary <ushort, Node>(); playerNodes = new Dictionary <Character, Node>(); stateHistory = new Dictionary <ushort, Godot.Collections.Array>(); specialNodes = new List <Node>(); playerOperation = new System.Threading.Mutex(); lastEntityId = 0; ticks = 0; timeout = 0; GetNode("InGame").Call("load_map", mapId); map = GetNode("InGame/Map"); entityRoot = GetNode("InGame/Entities"); GetNode <Godot.Timer>("Timer").Connect("timeout", this, "Tick"); GD.Print("Created new room of map ", mapId); }
static void Main() { try { //设置应用程序处理异常方式:ThreadException处理 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //处理UI线程异常 Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); //处理非UI线程异常 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); bool blIsRuned; System.Threading.Mutex mutex = new System.Threading.Mutex(true, "云访客门禁网络通信助手", out blIsRuned); if (blIsRuned == true) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new LoginFrm()); if (LoginFrm.strFlag_Login == "1") { //Application.Run(new Form1()); Application.Run(new D_RemoterControlFrm()); mutex.ReleaseMutex();//释放进程一次 } else { Application.Exit(); } } else { MessageBox.Show("云访客门禁网络通信助手已经在运行,请不要重复开启此系统!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (Exception ex) { string str = GetExceptionMsg(ex, string.Empty); MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
static void Main() { try { #if ShowToDo Program.showToDo = true; #else Program.showToDo = false; #endif bool blnOK; Cursor.Current = Cursors.WaitCursor; using (System.Threading.Mutex mut = new System.Threading.Mutex(true, "Anwendungsname", out blnOK)) { if (blnOK) { AppDomain.CurrentDomain.UnhandledException += Program.CurrentDomain_UnhandledException; Application.ThreadException += Program.Application_ThreadException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Program.ED_IBE_Context = new EDIBEApplicationContext(); Application.Run(Program.ED_IBE_Context); } else { MessageBox.Show("A instance of ED-IBE is already running!", "Aborted !", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); } } Cursor.Current = Cursors.Default; } catch (Exception ex) { Cursor.Current = Cursors.Default; CErr.processError(ex, "Error in main routine !"); } }
public virtual void AddDirectoryAccess(string path, FileAccess access, string user) { using (var dirMutex = new System.Threading.Mutex(false, path.Replace('\\', '_'))) { dirMutex.WaitOne(); try { DirectorySecurity security = fileSystem.GetDirectoryAccessSecurity(path); foreach (FileSystemAccessRule rule in GetAccessControlRules(access, user)) { security.AddAccessRule(rule); } fileSystem.SetDirectoryAccessSecurity(path, security); } finally { dirMutex.ReleaseMutex(); } } }
static void Main() { bool mutexCreated = false; System.Threading.Mutex mutex = new System.Threading.Mutex(true, @"xcapSnappingTool", out mutexCreated); if (mutexCreated) { Thread t1 = new Thread(new ThreadStart(SplashForm)); t1.Name = "Splash"; t1.Start(); Thread.Sleep(1000); t1.Abort(); new Snap(); } else { mutex.Dispose(); Application.Exit(); return; } }
static void Main() { //是否可以打开新进程 bool runOne = false; //获取程序集Guid作为唯一标识 Attribute AttGuid = Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute)); string cKeyGuid = ((GuidAttribute)AttGuid).Value; Mutex mux = new System.Threading.Mutex(true, cKeyGuid, out runOne); if (!runOne) { Environment.Exit(1); } else { INIConfig.setConfigFile(Application.StartupPath + @"\Config.ini"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmTask()); mux.ReleaseMutex(); } }
static void Main(string[] args) { #region Credit to http://stackoverflow.com/questions/6486195/ensuring-only-one-application-instance bool firstInstance; var mutex = new System.Threading.Mutex(true, "UniqueAppId", out firstInstance); if (!firstInstance) { return; } #endregion Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Images.Array = args; Application.Run(new Form1()); GC.KeepAlive(mutex); }
private void FeedSyncWorker(object o) { System.Threading.Mutex ThreadFeedSync = System.Threading.Mutex.OpenExisting("FeedSyncMutex"); ThreadFeedSync.WaitOne(); XmlDocument doc = new XmlDocument(); Log.Debug("ABCiView2Util: FeedSync Worker Thread Begin"); string feedData = GetWebData(o as String); // TVFeed has been known to contain invalid characters. // Need to convert to spaces doc.LoadXml(SanitizeXml(feedData)); XmlNamespaceManager nsmRequest = new XmlNamespaceManager(doc.NameTable); nsmRequest.AddNamespace("a", "http://namespace.feedsync"); XmlNodeList nodes = doc.GetElementsByTagName("asset"); foreach (XmlNode node in nodes) { if (node["type"].InnerText == "video") { ProgramData programData; programData.title = node["title"].InnerText; programData.description = node["description"].InnerText; programData.playURL = node["assetUrl"].InnerText; if (!ProgramDictionary.ContainsKey(node["id"].InnerText)) { ProgramDictionary.Add(node["id"].InnerText, programData); } } } ThreadFeedSync.ReleaseMutex(); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { //if we are not waiting for a cancel, keep rolling while (backgroundWorker1.CancellationPending == false) { //grab the app mutex and run automation cycle System.Threading.Mutex appMutex = new System.Threading.Mutex(false, "RiskAppsAutomation"); //don't wait for ever if (appMutex.WaitOne(automation_interval, false)) { //run automation RunAutomationCycle(); // give back the mutex appMutex.ReleaseMutex(); } //this is a tight loop, so don't be a hog Thread.Sleep(automation_interval); } }
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(); }