Esempio n. 1
0
 private void FindProcess()
 {
     if (RefreshProcess())
     {
         ProcessStarted?.Invoke(this, new EventArgs());
     }
 }
Esempio n. 2
0
        private void Run()
        {
            while (_running)
            {
                if (_currentProcess == null)
                {
                    Process[] processes = Process.GetProcessesByName(_processName);
                    if (processes.Length > 0)
                    {
                        _currentProcess = processes[0];
                        ProcessStarted?.Invoke(this, new ProcessEventArgs
                        {
                            Process = _currentProcess
                        });
                    }
                }

                if (_currentProcess != null)
                {
                    if (_currentProcess.HasExited)
                    {
                        ProcessStopped?.Invoke(this, new ProcessEventArgs
                        {
                            Process = _currentProcess
                        });
                        _currentProcess = null;
                    }
                }

                Thread.Sleep(500);
            }
        }
Esempio n. 3
0
        public void LaunchProcessInteractively(string filename)
        {
            var  p = this;
            uint processId;
            var  started = p.LaunchProcessSuspended(filename, InitialResumeTime, out processId);

            string okMessage;
            string title;

            if (started)
            {
                okMessage = $"The Process started with PID {processId}.\r\nClose this dialog to resume it.";
                title     = "Process started";
            }
            else
            {
                okMessage = $"Error launching file {filename}";
                if (ProcessStarted == null)
                {
                    throw new ProcessLauncherException(okMessage);
                }
                title = "Error launching file";
            }
            var processLaunchedEventArgs = new ProcessLaunchedEventArgs(started, okMessage, title);

            ProcessStarted?.Invoke(this, processLaunchedEventArgs);

            p.ResumeProcess();
        }
Esempio n. 4
0
 /// <summary>
 /// 执行一段命令
 /// </summary>
 /// <param name="command">命令</param>
 /// <param name="user">用户类型</param>
 /// <param name="suCheck">当root执行时,检测su是否存在并根据情况抛出异常</param>
 /// <returns></returns>
 public AdvanceOutput Execute(string command, LinuxUser user = LinuxUser.Normal, bool suCheck = true)
 {
     lock (exeLock)
     {
         outputBuilder.Clear();
         if (user == LinuxUser.Su && suCheck && !HaveSu())
         {
             throw new DeviceHaveNoRootException(device);
         }
         string shellCommand = user == LinuxUser.Normal ? command : $"su -c \'{command}\'";
         string fullCommand  = $"{device.ToFullSerial()} shell \"{shellCommand} ; exit $?\"";
         pStartInfo.Arguments = fullCommand;
         using (var process = new Process())
         {
             process.StartInfo           = pStartInfo;
             process.OutputDataReceived += (s, e) => { OnOutputReceived(e, false); };
             process.ErrorDataReceived  += (s, e) => { OnOutputReceived(e, true); };
             process.Start();
             process.BeginOutputReadLine();
             process.BeginErrorReadLine();
             ProcessStarted?.Invoke(this, new ProcessStartedEventArgs(process.Id));
             process.WaitForExit();
             process.CancelErrorRead();
             process.CancelOutputRead();
             outputBuilder.ExitCode = process.ExitCode;
         }
         return(outputBuilder.Result);
     }
 }
Esempio n. 5
0
 public void Start()
 {
     MainWindow.This.Dispatcher.Invoke(() =>
     {
         if (Status == ServerInfoStatus.Stopped)
         {
             try
             {
                 Status            = ServerInfoStatus.Started;
                 CurrentServerBase = new ServerProcessInfoBase();
                 CurrentServerBase.Start("App_" + Name, AssemblyPath);
                 ServerInfoPage.SendToMainHostForHidden(CurrentServerBase.BaseProcess);
                 ProcessStarted?.Invoke();
             }
             catch (Exception ex)
             {
                 AutoLogger.Default.LogError(ex, "StartServer");
                 if (CurrentServerBase != null)
                 {
                     CurrentServerBase.Dispose();
                     CurrentServerBase = null;
                 }
                 Status = ServerInfoStatus.Stopped;
             }
             SettingInfo.SaveSettingInfo();
         }
     });
 }
        public void IgnoreAProcessEndedEventForAUnkownProcess()
        {
            Guid           guid        = Guid.NewGuid();
            Guid           guid2       = Guid.NewGuid();
            Guid           processType = ProcessGuids.ProcessA;
            ProcessStarted worEvent    = new ProcessStarted(guid, processType);
            ProcessEnded   worcEvent   = new ProcessEnded(guid2, DateTime.UtcNow, false);

            IRepository <DailyActivity> repo = GetRepositoryForTest();

            DailyActivityEventProcessor processor = new DailyActivityEventProcessor(
                repo
                );

            processor.Handle(worEvent);
            processor.Handle(worcEvent);

            DailyActivity activity = repo.Get(GetIdForFirstActivityPersisted(repo));

            Assert.IsNotNull(activity);
            Assert.AreEqual(1, activity.ActiveProcesses);
            Assert.AreEqual(1, activity.TotalProcessCount);
            Assert.AreEqual(0, activity.CompletionCount);
            Assert.AreEqual(0, activity.CompletedWithErrorCount);
        }
        public void CanProcessProcessStartedEvents()
        {
            Guid guid1 = Guid.NewGuid();
            Guid guid2 = Guid.NewGuid();
            Guid guid3 = Guid.NewGuid();

            Guid processA = ProcessGuids.ProcessA;
            Guid processB = ProcessGuids.ProcessB;

            ProcessStarted startA1 = new ProcessStarted(guid1, processA);
            ProcessStarted startB1 = new ProcessStarted(guid2, processB);
            ProcessStarted startA2 = new ProcessStarted(guid3, processA);

            IRepository <ProcessTypeCount> repo = GetRepositoryForTest();

            ProcessTypeCounterEventProcessor processor = new ProcessTypeCounterEventProcessor(
                repo
                );

            processor.Handle(startA1);
            processor.Handle(startB1);
            processor.Handle(startA2);

            ProcessTypeCount counterA = repo.Get(processA.ToString());

            Assert.IsNotNull(counterA);
            Assert.AreEqual(2, counterA.Count);

            ProcessTypeCount counterB = repo.Get(processB.ToString());

            Assert.IsNotNull(counterB);
            Assert.AreEqual(1, counterB.Count);
        }
Esempio n. 8
0
        /// <inheritdoc />
        public void Start()
        {
            Contract.Requires(!Started, "Process was already started.  Cannot start process more than once.");

            Started = true;
            m_processExecutor.Start();
            ProcessStarted?.Invoke(ProcessId);
        }
Esempio n. 9
0
 public void StartProcess(string name)
 {
     if (_workers.ContainsKey(name) && !_workers[name].IsBusy)
     {
         ProcessStarted?.Invoke(this, _workers[name]);
         _workers[name].RunWorkerAsync();
     }
 }
 private Task NofificarInicio()
 {
     return (ProcessStarted?.Invoke(this, new ExecutorStartEventArgs()
     {
         JobId = this.JobId,
         FechaInicio = DateTime.Now
     }) ?? Task.CompletedTask);//.ConfigureAwait(false);
 }
Esempio n. 11
0
        /// <inheritdoc />
        public void Start()
        {
            Contract.Requires(!Started, "Process was already started.  Cannot start process more than once.");

            SetExecutePermissionIfNeeded(Process.StartInfo.FileName);

            Started = true;
            m_processExecutor.Start();
            ProcessStarted?.Invoke(ProcessId);
        }
Esempio n. 12
0
 /// <summary>
 /// 进程启动了,进行一些流处理等操作
 /// </summary>
 /// <param name="process"></param>
 protected virtual void OnProcessStarted(Process process)
 {
     if (process.StartInfo.RedirectStandardOutput)
     {
         process.OutputDataReceived += (s, e) => RaiseOutputReceived(e, false);
         process.ErrorDataReceived  += (s, e) => RaiseOutputReceived(e, true);
         currentProcess.BeginOutputReadLine();
         currentProcess.BeginErrorReadLine();
     }
     ProcessStarted?.Invoke(this, new ProcessEventArgs(process));
 }
Esempio n. 13
0
            public int ExecuteToEnd()
            {
                Start();
                ProcessStarted?.Invoke(this, new ProcessStartedEventArgs(Id));
                BeginOutputReadLine();
                BeginErrorReadLine();
                WaitForExit();
                int ret = ExitCode;

                CancelErrorRead();
                CancelOutputRead();
                return(ret);
            }
Esempio n. 14
0
        public void ApplyEvent(ProcessStarted @event)
        {
            var process = new ProcessInfo
            {
                Id          = @event.ProcessId,
                StartTime   = @event.StartTime,
                ProcessName = @event.ProcessName,
                HandleCount = @event.HandleCount,
                WorkingSet  = @event.WorkingSet
            };

            _processes.Add(process);
        }
Esempio n. 15
0
 /// <summary>
 /// 连接到设备上
 /// </summary>
 /// <param name="asSuperuser"></param>
 public void Connect(bool asSuperuser = false)
 {
     _mainProcess.Start();
     ProcessStarted?.Invoke(this, new ProcessStartedEventArgs(_mainProcess.Id));
     _mainProcess.BeginOutputReadLine();
     _mainProcess.BeginErrorReadLine();
     IsConnect = true;
     if (asSuperuser)
     {
         Switch2Su();
     }
     Thread.Sleep(200);
 }
        public void CanCreateInstanceOfProcessEndedEvent()
        {
            Guid     processId   = Guid.NewGuid();
            Guid     processType = ProcessGuids.ProcessA;
            DateTime time        = DateTime.UtcNow;


            ProcessStarted @event = new ProcessStarted(processId, processType);

            Assert.IsNotNull(@event);
            Assert.IsInstanceOf <Event>(@event);

            Assert.AreEqual(processId, @event.ProcessId);
            Assert.AreEqual(processType, @event.ProcessTypeId);
        }
        private void Tick(object sender, ElapsedEventArgs e)
        {
            var oldCache = this.ProcessCache;

            this.UpdateProcessCache();
            var(deleted, added) = oldCache.GetFullDifferenceTo(this.ProcessCache);

            foreach (var add in added)
            {
                ProcessStarted?.Invoke(this, new ProcessEventArgs(add.Value));
            }
            foreach (var del in deleted)
            {
                ProcessStopped?.Invoke(this, new ProcessEventArgs(del.Value));
            }
        }
Esempio n. 18
0
        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            Process[] newProcesses = Process.GetProcesses();
            foreach (Process startedProcess in newProcesses.Except(_lastScannedProcesses, _comparer))
            {
                ProcessStarted?.Invoke(this, new ProcessEventArgs(startedProcess));
                _logger.Verbose("Started Process: {startedProcess}", startedProcess.ProcessName);
            }

            foreach (Process stoppedProcess in _lastScannedProcesses.Except(newProcesses, _comparer))
            {
                ProcessStopped?.Invoke(this, new ProcessEventArgs(stoppedProcess));
                _logger.Verbose("Stopped Process: {stoppedProcess}", stoppedProcess.ProcessName);
            }

            _lastScannedProcesses = newProcesses;
        }
Esempio n. 19
0
        /// <inheritdoc />
        public void Start()
        {
            Contract.Requires(!Started, "Process was already started.  Cannot start process more than once.");

            m_processExecutor = new AsyncProcessExecutor(
                CreateProcess(),
                ProcessInfo.Timeout ?? TimeSpan.FromMinutes(10),
                line => FeedStdOut(m_output, line),
                line => FeedStdErr(m_error, line),
                ProcessInfo,
                msg => LogProcessState(msg));

            m_processExecutor.Start();

            ProcessStarted?.Invoke();

            ProcessInfo.ProcessIdListener?.Invoke(ProcessId);
        }
Esempio n. 20
0
        public static ObservableCollection <(MemoryStream stream, string name)> RunDumper()
        {
            File.WriteAllBytes("titledumper.exe", Properties.Resources.titledumper);
            DumperProcess = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow         = true,
                    UseShellExecute        = false,
                    WindowStyle            = ProcessWindowStyle.Hidden,
                    RedirectStandardOutput = true,
                    FileName  = "titledumper.exe",
                    Arguments = $"/vol/code ${Directory.GetCurrentDirectory()}/output"
                }
            };
            DumperProcess.Start();
            ProcessStarted?.Invoke(DumperProcess);
            while (!DumperProcess.HasExited)
            {
                if (DumperProcess.HasExited)
                {
                    break;
                }
            }
            var list = new ObservableCollection <(MemoryStream stream, string name)>();

            foreach (var d in new DirectoryInfo(Directory.GetCurrentDirectory()).GetDirectories())
            {
                if (d.FullName.EndsWith("output"))
                {
                    foreach (var f in d.GetFiles())
                    {
                        if (f.Extension is ".rpx")
                        {
                            list.Add((new MemoryStream(File.ReadAllBytes(f.FullName)), f.Name));
                        }
                    }
                }
            }
            File.Delete("titledumper.exe");
            return(list);
        }
Esempio n. 21
0
 private void run(object o, DoWorkEventArgs args)
 {
     ProcessStarted?.Invoke(this, EventArgs.Empty);
     while (!_stopCalled)
     {
         lock (_config)
         {
             foreach (var rule in _config.Rules)
             {
                 IntPtr address = new IntPtr(_baseMemoryOffset + rule.MemoryOffset64);
                 var    bytes   = _process.ReadArray <byte>(address, rule.NumBytes);
                 if (rule.Bytes == null)
                 {
                     rule.Bytes = bytes;
                     continue;
                 }
                 else
                 {
                     IChangedDataContainer changedBytes;
                     if (isBytesChangedAccordingToRule(bytes, rule, out changedBytes))
                     {
                         rule.Bytes = bytes;
                         OnLog(rule, "You");
                         MemoryChanged?.Invoke(this, new MemoryChangedEventArgs(rule, changedBytes));
                     }
                     else
                     {
                         rule.Bytes = bytes;
                     }
                 }
             }
         }
         Thread.Sleep(_pollIntervall);
         //Update config if request has been made
         if (_nextConfig != null)
         {
             _config     = _nextConfig;
             _nextConfig = null;
         }
     }
 }
Esempio n. 22
0
        public void CanInstallHandlersInTheContainer()
        {
            using (IWindsorContainer container = new WindsorContainer())
            {
                //This line just forces the domain events lib to be loaded, and handlers available in the app domain.
                IProcessEvents proc = new DailyActivityEventProcessor(new Mock <IRepository <DailyActivity> >().Object);

                container.Install(new HandlerInstaller(), new RepositoryInstaller());

                ProcessStarted started     = new ProcessStarted(Guid.NewGuid(), Guid.NewGuid());
                var            handlerType = typeof(IHandleEvent <>).MakeGenericType(started.GetType());

                IEnumerable <dynamic> handlers = container.ResolveAll(handlerType).Cast <dynamic>();

                Assert.IsNotNull(handlers);
                Assert.AreEqual(2, handlers.Count());

                var handler = handlers.FirstOrDefault(o => o.GetType() == typeof(DailyActivityEventProcessor));
                Assert.IsNotNull(handler);
            }
        }
Esempio n. 23
0
        void Watch(object sender, EventArgs e)
        {
            List <Process> updatedProcesses = Process.GetProcesses().ToList(); //Create a variable for the updated processes list.

            if (updatedProcesses != processes)                                 //If the process list is different from the updated version...
            {
                if (updatedProcesses.Count < processes.Count)                  //If the updated list is smaller, which means that a process was killed...
                {
                    Debug.WriteLine("processes.Count: " + processes.Count);
                    Debug.WriteLine("updatedProcesses.Count: " + updatedProcesses.Count);
                    ProcessKilled?.Invoke(this, new ProcessEventArgs(GetKilledProcesses(updatedProcesses))); //Invoke the ProcessKilled event with the process that was killed.
                }
                if (updatedProcesses.Count > processes.Count)                                                //If the updated list is larger, which means that a new process was started...
                {
                    Debug.WriteLine("processes.Count: " + processes.Count);
                    Debug.WriteLine("updatedProcesses.Count: " + updatedProcesses.Count);
                    ProcessStarted?.Invoke(this, new ProcessEventArgs(GetStartedProcesses(updatedProcesses))); //Invoke the ProcessStarted event with the process that was started.
                }
            }
            processes = new List <Process>(updatedProcesses); //Replace the process list with the updated version.
        }
Esempio n. 24
0
 /// <summary>
 /// 执行一段命令或运行某个程序
 /// </summary>
 /// <param name="fileName">文件路径</param>
 /// <param name="args">命令或参数</param>
 /// <returns></returns>
 public AdvanceOutput Execute(string fileName, string args)
 {
     lock (_lock)
     {
         _builder.Clear();
         int exitCode = 404;
         _startInfo.FileName  = fileName;
         _startInfo.Arguments = args;
         using (var process = Process.Start(_startInfo))
         {
             process.OutputDataReceived += (s, e) => RaiseOutputReceived(e, false);
             process.ErrorDataReceived  += (s, e) => RaiseOutputReceived(e, true);
             process.BeginOutputReadLine();
             process.BeginErrorReadLine();
             ProcessStarted?.Invoke(this, new ProcessStartedEventArgs(process.Id));
             process.WaitForExit();
             process.CancelErrorRead();
             process.CancelOutputRead();
             exitCode = process.ExitCode;
         };
         return(new AdvanceOutput(_builder.ToOutput(), exitCode));
     }
 }
Esempio n. 25
0
        //====================================================================================== Agent manager methods

        private static void EnsureAgentProcess()
        {
            var startedCount = 0;

            try
            {
                for (var i = 0; i < _agentProcesses.Length; i++)
                {
                    if (_agentProcesses[i] == null || _agentProcesses[i].HasExited)
                    {
                        // start a new process, but do not wait for it
                        _agentProcesses[i] = Process.Start(new ProcessStartInfo(AgentPath));
                        startedCount++;

                        // notify outsiders
                        ProcessStarted?.Invoke(null, new AgentManagerEventArgs(_agentProcesses[i]));
                    }
                }
            }
            catch (Exception ex)
            {
                SnLog.WriteException(ex, "Agent start error. Agent path: " + AgentPath + ".",
                                     EventId.TaskManagement.Lifecycle);
                return;
            }

            if (startedCount > 0)
            {
                SnLog.WriteInformation($"{AGENT_PROCESSNAME} STARTED ({startedCount} new instance(s) from {AgentPath}).", EventId.TaskManagement.Lifecycle);
            }
            else if (++_counter >= 10)
            {
                _counter = 0;

                SnTrace.TaskManagement.Write("{0} is running ({1} instance(s) from {2}).", AGENT_PROCESSNAME, Configuration.TaskAgentCount, AgentPath);
            }
        }
 private void HandleProcessStarted(ProcessStarted @event)
 {
     _mainForm.Show();
 }
Esempio n. 27
0
 private void OnProcessStarted(ProcessStartedEventArgs e)
 {
     ProcessStarted?.Invoke(this, e);
 }
Esempio n. 28
0
 /// <summary>
 /// Invoked when process starts (first token is added)
 /// </summary>
 private void OnProcessStarted()
 {
     ProcessStarted ps = new ProcessStarted();
     ps.InstanceId = InstanceId;
     ps.DefinitionId = ProcessDefinitionId;
     ps.CorrelationId = CorrelationId;
     NotifyProcessEvent(ps);
 }
Esempio n. 29
0
        /// <summary>
        /// Runs specified process with specified arguments.
        /// </summary>
        /// <param name="fileName">The process to start.</param>
        /// <param name="arguments">The set of arguments to use when starting the process.</param>
        /// <returns>The process completion status.</returns>
        /// <exception cref="System.IO.FileNotFoundException">Occurs when the file to run is not found.</exception>
        /// <exception cref="InvalidOperationException">Occurs when this class instance is already running another process.</exception>
        public virtual CompletionStatus Run(string fileName, string arguments)
        {
            fileName.CheckNotNullOrEmpty(nameof(fileName));

            IProcess p;

            lock (LockToken)
            {
                if (WorkProcess != null)
                {
                    throw new InvalidOperationException(Resources.ProcessWorkerBusy);
                }
                p           = _factory.Create();
                WorkProcess = p;
            }
            _output.Clear();
            _cancelWork = new CancellationTokenSource();
            if (Options == null)
            {
                Options = new ProcessOptions();
            }

            p.StartInfo.FileName  = fileName;
            p.StartInfo.Arguments = arguments;
            CommandWithArgs       = $@"""{fileName}"" {arguments}".TrimEnd();

            if (OutputType == ProcessOutput.Output)
            {
                p.OutputDataReceived += OnDataReceived;
            }
            else if (OutputType == ProcessOutput.Error)
            {
                p.ErrorDataReceived += OnDataReceived;
            }

            if (Options.DisplayMode != ProcessDisplayMode.Native)
            {
                //if (Options.DisplayMode == ProcessDisplayMode.Interface && Config.UserInterfaceManager != null)
                //{
                //    Config.UserInterfaceManager.Display(Owner, this);
                //}

                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.WindowStyle    = ProcessWindowStyle.Hidden;
                if (OutputType == ProcessOutput.Output)
                {
                    p.StartInfo.RedirectStandardOutput = true;
                }
                else if (OutputType == ProcessOutput.Error)
                {
                    p.StartInfo.RedirectStandardError = true;
                }

                p.StartInfo.UseShellExecute = false;
            }

            ProcessStarted?.Invoke(this, new ProcessStartedEventArgs(this));

            p.Start();
            try
            {
                if (!p.HasExited)
                {
                    p.PriorityClass = Options.Priority;
                }
            }
            catch (System.ComponentModel.Win32Exception) { }
            catch (InvalidOperationException) { }

            if (Options.DisplayMode != ProcessDisplayMode.Native)
            {
                if (OutputType == ProcessOutput.Output)
                {
                    p.BeginOutputReadLine();
                }
                else if (OutputType == ProcessOutput.Error)
                {
                    p.BeginErrorReadLine();
                }
            }

            var timeout = Wait();

            // ExitCode is 0 for normal exit. Different value when closing the console.
            var result = timeout ? CompletionStatus.Timeout : _cancelWork.IsCancellationRequested ? CompletionStatus.Cancelled : p.ExitCode == 0 ? CompletionStatus.Success : CompletionStatus.Failed;

            _cancelWork = null;
            // Allow changing CompletionStatus in ProcessCompleted.
            var completedArgs = new ProcessCompletedEventArgs(result);

            ProcessCompleted?.Invoke(this, completedArgs);
            result = completedArgs.Status;
            LastCompletionStatus = result;
            //if ((result == CompletionStatus.Failed || result == CompletionStatus.Timeout) && Options.DisplayMode == ProcessDisplayMode.ErrorOnly)
            //{
            //    Config.UserInterfaceManager?.DisplayError(Owner, this);
            //}

            WorkProcess = null;
            return(result);
        }
Esempio n. 30
0
        /// <summary>
        /// Runs specified application with specified arguments.
        /// </summary>
        /// <param name="fileName">The application to start.</param>
        /// <param name="arguments">The set of arguments to use when starting the application.</param>
        /// <returns>The process completion status.</returns>
        /// <exception cref="System.IO.FileNotFoundException">Occurs when the file to run is not found.</exception>
        /// <exception cref="InvalidOperationException">Occurs when this class instance is already running another process.</exception>
        public virtual CompletionStatus Run(string fileName, string arguments)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentException("Filename cannot be null or empty.", nameof(fileName));
            }
            if (!fileSystem.Exists(fileName))
            {
                throw new System.IO.FileNotFoundException(string.Format(@"File ""{0}"" is not found.", fileName));
            }
            IProcess P;

            lock (lockToken) {
                if (WorkProcess != null)
                {
                    throw new InvalidOperationException("This instance of FFmpegProcess is busy. You can run concurrent commands by creating other class instances.");
                }
                P           = factory.Create();
                WorkProcess = P;
            }
            output.Clear();
            cancelWork = new CancellationTokenSource();
            if (Options == null)
            {
                Options = new ProcessOptions();
            }

            P.StartInfo.FileName  = fileName;
            P.StartInfo.Arguments = arguments;
            CommandWithArgs       = string.Format(@"""{0}"" {1}", fileName, arguments).TrimEnd();

            if (OutputType == ProcessOutput.Output)
            {
                P.OutputDataReceived += OnDataReceived;
            }
            else if (OutputType == ProcessOutput.Error)
            {
                P.ErrorDataReceived += OnDataReceived;
            }

            if (Options.DisplayMode != FFmpegDisplayMode.Native)
            {
                if (Options.DisplayMode == FFmpegDisplayMode.Interface && Config.UserInterfaceManager != null)
                {
                    Config.UserInterfaceManager.Display(this);
                }
                P.StartInfo.CreateNoWindow = true;
                P.StartInfo.WindowStyle    = ProcessWindowStyle.Hidden;
                if (OutputType == ProcessOutput.Output)
                {
                    P.StartInfo.RedirectStandardOutput = true;
                }
                else if (OutputType == ProcessOutput.Error)
                {
                    P.StartInfo.RedirectStandardError = true;
                }
                P.StartInfo.UseShellExecute = false;
            }

            ProcessStarted?.Invoke(this, new ProcessStartedEventArgs(this));

            P.Start();
            try {
                if (!P.HasExited)
                {
                    P.PriorityClass = Options.Priority;
                }
            } catch { }
            if (Options.DisplayMode != FFmpegDisplayMode.Native)
            {
                if (OutputType == ProcessOutput.Output)
                {
                    P.BeginOutputReadLine();
                }
                else if (OutputType == ProcessOutput.Error)
                {
                    P.BeginErrorReadLine();
                }
            }

            bool Timeout = Wait();

            // ExitCode is 0 for normal exit. Different value when closing the console.
            CompletionStatus Result = Timeout ? CompletionStatus.Timeout : cancelWork.IsCancellationRequested ? CompletionStatus.Cancelled : P.ExitCode == 0 ? CompletionStatus.Success : CompletionStatus.Failed;

            cancelWork           = null;
            LastCompletionStatus = Result;
            ProcessCompleted?.Invoke(this, new ProcessCompletedEventArgs(Result));
            if ((Result == CompletionStatus.Failed || Result == CompletionStatus.Timeout) && Options.DisplayMode == FFmpegDisplayMode.ErrorOnly)
            {
                Config.UserInterfaceManager?.DisplayError(this);
            }

            WorkProcess = null;
            return(Result);
        }
Esempio n. 31
0
 private void OnProcessStartedChange(object sender, ProcessArgs e)
 {
     ProcessStarted?.Invoke(sender, e);
 }
Esempio n. 32
0
 protected virtual void OnProcessStarted(DebuggeeProcessEventArgs e)
 {
     ProcessStarted?.Invoke(this, e);
 }