A single session of the console emulator running a console process. Each console process execution in the control spawns a new console emulator and a new session.

When the console emulator starts, a console view appears in the control. The console process starts running in it immediately. When the console process terminates, the console emulator might or might not be closed, depending on the settings. After the console emulator closes, the control stops viewing the console, and this session ends.

        public ConEmuSession Start([NotNull] ConEmuStartInfo startinfo)
        {
            if (startinfo == null)
            {
                throw new ArgumentNullException(nameof(startinfo));
            }

            // Close prev session if there is one
            _running?.CloseConsoleEmulator();
            if (_running != null)
            {
                throw new InvalidOperationException("Cannot start a new console process because another console emulator session has failed to close in due time.");
            }

            _autostartinfo = null;             // As we're starting, no more chance for an autostart
            if (!IsHandleCreated)
            {
                CreateHandle();
            }

            // Spawn session
            var session = new ConEmuSession(startinfo, new ConEmuSession.HostContext((void *)Handle, IsStatusbarVisible));

            _running = session;
            StateChanged?.Invoke(this, EventArgs.Empty);
            startinfo.ConsoleProcessPreExitedEventSink += (sender, args) => OnSessionEnds();
            // Wait for its exit
            session.WaitForConsoleEmulatorCloseAsync().ContinueWith(scheduler: TaskScheduler.FromCurrentSynchronizationContext(), continuationAction: task =>
            {
                OnSessionEnds();
            });

            return(session);
        }
        internal GuiMacroBuilder([NotNull] ConEmuSession owner, [NotNull] string sMacroName, [NotNull] IEnumerable<string> parameters)
        {
            if(owner == null)
                throw new ArgumentNullException(nameof(owner));
            if(sMacroName == null)
                throw new ArgumentNullException(nameof(sMacroName));
            if(parameters == null)
                throw new ArgumentNullException(nameof(parameters));

            _owner = owner;
            _sMacroName = sMacroName;
            _parameters = parameters;
        }
 private void OnSessionEnds()
 {
     try
     {
         _nLastExitCode = _running.GetConsoleProcessExitCode();
     }
     catch (Exception)
     {
         // NOP
     }
     _running = null;
     Invalidate();
     StateChanged?.Invoke(this, EventArgs.Empty);
 }
Beispiel #4
0
        internal GuiMacroBuilder([NotNull] ConEmuSession owner, [NotNull] string sMacroName, [NotNull] IEnumerable <string> parameters)
        {
            if (owner == null)
            {
                throw new ArgumentNullException(nameof(owner));
            }
            if (sMacroName == null)
            {
                throw new ArgumentNullException(nameof(sMacroName));
            }
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            _owner      = owner;
            _sMacroName = sMacroName;
            _parameters = parameters;
        }
 private void StartPowerShellExecutionHost()
 {
     if (!IsConEmuInstalled)
     {
         return;
     }
     var config = core.Config;
     var hostScript = Path.Combine(config.GetStringValue(PropertyKeys.BenchScripts), PowerShellHostScript);
     if (!File.Exists(hostScript))
     {
         throw new FileNotFoundException("The PowerShell host script was not found.");
     }
     currentToken = Guid.NewGuid().ToString("D");
     var cwd = config.GetStringValue(PropertyKeys.BenchRoot);
     var startInfo = BuildStartInfo(cwd, PowerShell.Executable,
         "\"" + string.Join(" ", "-NoProfile", "-NoLogo",
             "-ExecutionPolicy", "Unrestricted",
             "-File", "\"" + hostScript + "\"",
             "-Token", currentToken));
     currentSession = StartProcess(startInfo);
     currentSession.ConsoleEmulatorClosed += (s, o) =>
     {
         currentToken = null;
         currentSession = null;
     };
 }
Beispiel #6
0
		/// <summary>
		/// This method checks that the async-await compiler syntax is not prevented in netfx45+ projects due to the shim types present in the conemu assembly (https://github.com/Maximus5/conemu-inside/issues/20).
		/// </summary>
		private static async Task ShowMessageForChoiceAsync(ConEmuSession session)
		{
			if(session == null)
				throw new ArgumentNullException(nameof(session));
			ConsoleProcessExitedEventArgs exitargs = await session.WaitForConsoleProcessExitAsync();
			MessageBox.Show($"Your choice is {exitargs.ExitCode} (powered by wait-for-exit-async).");
		}
Beispiel #7
0
        public static async Task <GetInfoRoot> QueryAsync([NotNull] ConEmuSession session)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }

            GuiMacroResult result = await session.BeginGuiMacro("GetInfo").WithParam("Root").ExecuteAsync();

            Trace.WriteLine("[ROOT]: " + result.Response);
            if (!result.IsSuccessful)
            {
                throw new InvalidOperationException("The GetInfo-Root call did not succeed.");
            }
            if (string.IsNullOrWhiteSpace(result.Response))            // Might yield an empty string randomly if not ready yet
            {
                throw new InvalidOperationException("The GetInfo-Root call has yielded an empty result.");
            }

            // Interpret the string as XML
            var xmlDoc = new XmlDocument();

            try
            {
                xmlDoc.LoadXml(result.Response);
            }
            catch (Exception ex)
            {
                // Could not parse the XML response. Not expected. Wait more.
                throw new InvalidOperationException($"The GetInfo-Root call result “{result.Response}” were not a valid XML document.", ex);
            }
            XmlElement xmlRoot = xmlDoc.DocumentElement;

            if (xmlRoot == null)
            {
                throw new InvalidOperationException($"The GetInfo-Root call result “{result.Response}” didn't have a root XML element.");
            }

            // Current possible records:
            // <Root State="NotStarted" Name="cmd.exe" />
            // <Root State="Running" Name="cmd.exe" PID="4672" ExitCode="259" UpTime="4406" />
            // <Root State="Exited" Name="cmd.exe" PID="4672" ExitCode="0" UpTime="14364"/>
            // Also, there's the State="Empty" documented, though it would be hard to catch

            // Start with detecting the state
            string sState = xmlRoot.GetAttribute("State");

            if (string.IsNullOrWhiteSpace(sState))
            {
                throw new InvalidOperationException($"The GetInfo-Root call result “{result.Response}” didn't specify the current ConEmu state.");
            }
            States state;

            if (!Enum.TryParse(sState, false, out state))
            {
                throw new InvalidOperationException($"The GetInfo-Root call result “{result.Response}” specifies the State “{sState}” which cannot be matched against the list of the known states {Enum.GetValues(typeof(States)).OfType<States>().Select(o => o.ToString()).OrderBy(o => o, StringComparer.InvariantCultureIgnoreCase).Aggregate((x, y) => x + ", " + y)}.");
            }

            string sName = xmlRoot.GetAttribute("Name");

            uint nPidRaw;
            uint?nPid = ((state == States.Running) && (uint.TryParse(xmlRoot.GetAttribute("PID"), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out nPidRaw))) ? nPidRaw : default(uint?);

            int nExitCodeRaw;
            int?nExitCode = ((state == States.Exited) && (int.TryParse(xmlRoot.GetAttribute("ExitCode"), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out nExitCodeRaw))) ? nExitCodeRaw : default(int?);

            return(new GetInfoRoot(state, sName, nPid, nExitCode));
        }
        public ConEmuSession Start([NotNull] ConEmuStartInfo startinfo)
        {
            if(startinfo == null)
                throw new ArgumentNullException(nameof(startinfo));

            // Close prev session if there is one
            _running?.CloseConsoleEmulator();
            if(_running != null)
                throw new InvalidOperationException("Cannot start a new console process because another console emulator session has failed to close in due time.");

            _autostartinfo = null; // As we're starting, no more chance for an autostart
            if(!IsHandleCreated)
                CreateHandle();

            // Spawn session
            var session = new ConEmuSession(startinfo, new ConEmuSession.HostContext((void*)Handle, IsStatusbarVisible));
            _running = session;
            StateChanged?.Invoke(this, EventArgs.Empty);

            // Wait for its exit
            session.WaitForConsoleEmulatorCloseAsync().ContinueWith(scheduler : TaskScheduler.FromCurrentSynchronizationContext(), continuationAction : task =>
            {
                try
                {
                    _nLastExitCode = _running.GetConsoleProcessExitCode();
                }
                catch(Exception)
                {
                    // NOP
                }
                _running = null;
                Invalidate();
                StateChanged?.Invoke(this, EventArgs.Empty);
            });

            return session;
        }
Beispiel #9
0
        public ConEmuSession Start([NotNull] ConEmuStartInfo startinfo, [NotNull] JoinableTaskFactory joinableTaskFactory,
                                   [NotNull] string conEmuStyle, string conEmuFontSize)
        {
            if (startinfo == null)
            {
                throw new ArgumentNullException(nameof(startinfo));
            }


            SetConsoleFontSize();

            SetConsoleStyle();

            // Close prev session if there is one
            _running?.CloseConsoleEmulator();
            if (_running != null)
            {
                throw new InvalidOperationException("Cannot start a new console process because another console emulator session has failed to close in due time.");
            }

            _autostartinfo = null;             // As we're starting, no more chance for an autostart
            if (!IsHandleCreated)
            {
                CreateHandle();
            }

            // Spawn session
            var session = new ConEmuSession(startinfo, new ConEmuSession.HostContext((void *)Handle, IsStatusbarVisible), joinableTaskFactory);

            _running = session;
            StateChanged?.Invoke(this, EventArgs.Empty);

            // Wait for its exit
            session.WaitForConsoleEmulatorCloseAsync().ContinueWith(scheduler: TaskScheduler.FromCurrentSynchronizationContext(), continuationAction: task =>
            {
                try
                {
                    _nLastExitCode = _running.GetConsoleProcessExitCode();
                }
                catch (Exception)
                {
                    // NOP
                }
                _running = null;
                Invalidate();
                StateChanged?.Invoke(this, EventArgs.Empty);
            }).Forget();

            return(session);

            void SetConsoleFontSize()
            {
                var startInfoBaseConfiguration = startinfo.BaseConfiguration;

                if (!string.IsNullOrWhiteSpace(conEmuFontSize))
                {
                    if (int.TryParse(conEmuFontSize, out var fontSize))
                    {
                        var nodeFontSize =
                            startInfoBaseConfiguration.SelectSingleNode("/key/key/key/value[@name='FontSize']");

                        if (nodeFontSize?.Attributes != null)
                        {
                            nodeFontSize.Attributes["data"].Value = fontSize.ToString("X8");
                        }
                    }
                }

                startinfo.BaseConfiguration = startInfoBaseConfiguration;
            }

            void SetConsoleStyle()
            {
                if (conEmuStyle != "Default")
                {
                    startinfo.ConsoleProcessExtraArgs = " -new_console:P:\"" + conEmuStyle + "\"";
                }
            }
        }