public static void Run(string appId, LaunchAction action, string[] args) { Mutex m_mutex = new Mutex(false, @"Local\" + appId); RunningObjectTable rot = new RunningObjectTable(); for (int i = 0; i < 120; i++) // wait for ~60 seconds { if (m_mutex.WaitOne(1, false)) { // we are the first instance try { using (rot.Register(appId, new OleCommandTargetImpl(action))) { action(args, true); } return; } finally { m_mutex.ReleaseMutex(); } } else { // we are not the first instance IOleCommandTargetWithExecParams instance = rot.GetObject(appId) as IOleCommandTargetWithExecParams; if (instance != null) { try { object dummy = null; object processId = null; instance.Exec(Guid.Empty, 0, OLECMDEXECOPT.DODEFAULT, ref dummy, ref processId); User32.AllowSetForegroundWindow((int)processId); object objArgs = args; object result = null; instance.Exec(Guid.Empty, 1, OLECMDEXECOPT.DODEFAULT, ref objArgs, ref result); if (result is bool && (bool)result) return; } catch (Exception e) { Trace.WriteLine(e.ToString()); } finally { Marshal.ReleaseComObject(instance); } } } Thread.Sleep(500); } Trace.WriteLine(appId + " could not start!"); }
public RegistrationHandle(RunningObjectTable rot, int registration) { _rot = rot; _registration = registration; }
public static void Run(string appId, LaunchAction action, string[] args) { Mutex m_mutex = new Mutex(false, @"Local\" + appId); RunningObjectTable rot = new RunningObjectTable(); for (int i = 0; i < 120; i++) // wait for ~60 seconds { if (m_mutex.WaitOne(1, false)) { // we are the first instance try { using (rot.Register(appId, new OleCommandTargetImpl(action))) { action(args, true); } return; } finally { m_mutex.ReleaseMutex(); } } else { // we are not the first instance IOleCommandTargetWithExecParams instance = rot.GetObject(appId) as IOleCommandTargetWithExecParams; if (instance != null) { try { object dummy = null; object processId = null; instance.Exec(Guid.Empty, 0, OLECMDEXECOPT.DODEFAULT, ref dummy, ref processId); User32.AllowSetForegroundWindow((int)processId); object objArgs = args; object result = null; instance.Exec(Guid.Empty, 1, OLECMDEXECOPT.DODEFAULT, ref objArgs, ref result); if (result is bool && (bool)result) { return; } } catch (Exception e) { Trace.WriteLine(e.ToString()); } finally { Marshal.ReleaseComObject(instance); } } } Thread.Sleep(500); } Trace.WriteLine(appId + " could not start!"); }