Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6863709
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T02:49:08+00:00 2026-05-27T02:49:08+00:00

I’ve got a web application that has a page full of batch files which

  • 0

I’ve got a web application that has a page full of batch files which the user can run, view the output, and send input. My problem occurs when the process hits something which causes it to pause, such as a pause, or a question that requires the user to press Y or N to continue. We’ll go with pause for the purposes of this question.

This is my batch file:

pause

When run in windows, I get the output displayed on my screen “Press any key to continue…”, I press enter, and it exits. But when my app runs this batch file, I dont get any output, but I know what it’s waiting for so I press enter, and only then do I see the output “Press any key to continue…”.

I’ve created a simplified version of my code in a console app, and the same thing happens, I get a blank screen, I press enter, and then I see “Press any key to continue…”

Any idea how I go about getting this line of output BEFORE I am required to press the key?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace BatchCaller
{
    class Program
    {
        static void Main(string[] args)
        {
            ProcessStartInfo psi = new ProcessStartInfo()
            {
                FileName = @"C:\Projects\BatchCaller\BatchCaller\Test2.bat",
                RedirectStandardOutput = true,
                RedirectStandardInput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            Process proc = new Process();

            proc.StartInfo = psi;
            proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
            proc.Start();
            proc.BeginOutputReadLine();

            // Problem is not here, ignore this, just my temporary input method.
            // Problem still occurs when these two lines are removed.
            string inputText = Console.ReadLine();
            proc.StandardInput.WriteLine(inputText);

            proc.WaitForExit();
        }

        static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            // This method doesnt get called for output: "Press any key to continue..."
            // Why?
            if (e.Data != null)
                Console.WriteLine(e.Data);
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T02:49:09+00:00Added an answer on May 27, 2026 at 2:49 am

    I realised it wasn’t reading the last line because the data received event was only being triggered after there was a whole line of output, but when it pauses or asks a question, the cursor is still on the same line. A new thread that continuously checked the output stream was the solution to this small problem.

    I also managed to solve my whole problem so that now what I’ve got when I run a script close ly resembles a command prompt window.

    Here’s a very basic summary of how it works:

    I start a new process that runs a batch file. At the same time I start a new thread that continuously loops asking the process for more output, and storing that output in a queue. My .NET timer continuously checks the queue for text, and outputs it into my ajax panel. I use a text box and ajax to input text into the process input and into my ajax panel. I also needed a lot of javascript and I had to use session variables to make it run smoothly.

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
        CodeBehind="Scripts.aspx.cs" Inherits="MITool.Scripts" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <script type="text/javascript" language="javascript">
            var script = '';
    
            function ShowScriptModal() {
                $('#overlay').css({ width: $(document).width(), height: $(document).height(), 'display': 'block' }).animate({ opacity: 0.85 }, 0, function () { $('#scriptModal').show(); });
            }
    
            function ScriptInputKeypress(e) {
                if (e.keyCode == 13) {
                    ScriptInput();
                }
            }
    
            function ScriptInput() {
                var txtInput = document.getElementById("txtInput");
                var input = txtInput.value;
                var hiddenInput = document.getElementById("hiddenInput");
    
                if (input == '')
                    return;
    
                hiddenInput.value = input;
    
                txtInput.value = '';
            }
    
            function CheckForNewOutput() {
                var outputUpdatePanel = document.getElementById("OutputUpdatePanel");
                var pageScript = outputUpdatePanel.innerHTML;
                if (script != pageScript) {
                    script = pageScript;
                    ScrollToBottom();
                }
                setTimeout("CheckForNewOutput()", 100);
            }
    
            function ScrollToBottom() {
                $('#OutputPanel').scrollTop($('#OutputUpdatePanel').height());
            }
        </script>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true" LoadScriptsBeforeUI="true" />
        <div id="scriptModal">
            <div id="ScriptInputOutput">
                <asp:Panel ID="OutputPanel" runat="server" Width="700" Height="250" ScrollBars="Vertical"
                    Style="margin: 10px auto; border: 1px solid #CCC; padding: 5px;" ClientIDMode="Static">
                    <controls:ScriptOutput ID="ScriptOutputControl" runat="server" />
                </asp:Panel>
                <asp:Panel ID="InputPanel" runat="server" DefaultButton="btnScriptInput" >
                    <asp:TextBox ID="txtInput" runat="server" ClientIDMode="Static" onkeypress="ScriptInputKeypress(event)" />
                    <asp:HiddenField ID="hiddenInput" runat="server" ClientIDMode="Static" />
                    <asp:Button ID="btnScriptInput" runat="server" Text="Script Input" ClientIDMode="Static" OnClick="btnScriptInput_Click" style="display:none" />           
                    <asp:Button ID="btnExit" runat="server" CssClass="floatRight" Text="Exit" OnClick="btnExit_Click" />
                </asp:Panel>
            </div>
        </div>
        <asp:Literal ID="litScript" runat="server" />
        <ul id="breadcrumb">
            <li><a href="/dashboard.aspx">Main page</a> &gt;</li>
            <li class="current">Scripts</li>
        </ul>
        <div class="content">
            <h2>
                <asp:Label ID="lblHeader" runat="server" Text="Scripts" /></h2>
            <div class="clear">
            </div>
            <div class="table-content">
                <asp:Label ID="lblMessage" runat="server" CssClass="redMessage" />
                <asp:Repeater ID="rptScripts" runat="server" OnItemCommand="rptScripts_ItemCommand">
                    <HeaderTemplate>
                        <table class="table" cellpadding="0" cellspacing="0">
                            <tr>
                                <th>
                                    ID
                                </th>
                                <th>
                                    Name
                                </th>
                                <th>
                                    Location
                                </th>
                                <th>
                                </th>
                            </tr>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <tr>
                            <td>
                                <%# Eval("ScriptId") %>
                            </td>
                            <td>
                                <%# Eval("Name") %>
                            </td>
                            <td>
                                <%# Eval("Path") %>
                            </td>
                            <td>
                                <asp:LinkButton ID="btnRunScript" runat="server" Text="Run" CommandName="Run" CommandArgument='<%# Eval("ScriptId") %>' />
                            </td>
                        </tr>
                    </ItemTemplate>
                    <FooterTemplate>
                        </table>
                    </FooterTemplate>
                </asp:Repeater>
                <div>
                </div>
            </div>
        </div>
        <script type="text/javascript" language="javascript">
            CheckForNewOutput();
        </script>
    </asp:Content>
    
    // ====== ====== ====== ====== ====== ====== ====== ====== ====== ====== ======//
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using MITool.Data.ScriptManager;
    using System.Diagnostics;
    using System.IO;
    using System.Web.Security;
    using System.Web.Services;
    using System.Collections.Concurrent;
    using System.Threading;
    
    namespace MITool
    {
        public partial class Scripts : System.Web.UI.Page
        {
            ConcurrentQueue<char> ScriptOutputQueue
            {
                get
                {
                    return (ConcurrentQueue<char>)Session["ScriptOutputQueue"];
                }
                set
                {
                    Session["ScriptOutputQueue"] = value;
                }
            }
            Process CurrentProcess
            {
                get
                {
                    return (Process)Session["CurrentProcess"];
                }
                set
                {
                    Session["CurrentProcess"] = value;
                }
            }
            bool ScriptRunning
            {
                get
                {
                    if (CurrentProcess == null)
                        return false;
                    if (!CurrentProcess.HasExited || !CurrentProcess.StandardOutput.EndOfStream)
                        return true;
                    return false;
                }
            }
            bool OutputProcessing
            {
                get
                {
                    if (ScriptOutputQueue != null && ScriptOutputQueue.Count != 0)
                        return true;
                    return false;
                }
            }
    
            Thread OutputThread;
    
            void Reset()
            {
                ScriptOutputControl.SetTimerEnabled(false);
                ScriptOutputControl.ClearOutputText();
                if (CurrentProcess != null && !CurrentProcess.HasExited)
                    CurrentProcess.Kill();
                if (OutputThread != null && OutputThread.IsAlive)
                    OutputThread.Abort();
                ScriptOutputQueue = new ConcurrentQueue<char>();
    
                litScript.Text = string.Empty;
                txtInput.Text = string.Empty;
            }
    
            void Page_Load(object sender, EventArgs e)
            {
                if (IsPostBack) return;
    
                Reset();
    
                FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                string role = id.Ticket.UserData;
    
                ScriptData data = new ScriptData();
                List<Script> scripts = data.GetScriptsByRole(role);
                rptScripts.DataSource = scripts;
                rptScripts.DataBind();
            }
    
            protected void rptScripts_ItemCommand(object source, RepeaterCommandEventArgs e)
            {
                switch (e.CommandName)
                {
                    case "Run": StartScript(Int32.Parse(e.CommandArgument.ToString()));
                        break;
                }
            }
    
            void StartScript(int id)
            {
                if (ScriptRunning || OutputProcessing)
                    return;
    
                Reset();
    
                ScriptData data = new ScriptData();
                History history = new History()
                {
                    UserName = HttpContext.Current.User.Identity.Name,
                    BatchFileId = id,
                    DateRun = DateTime.Now
                };
                data.CreateHistory(history);            
    
                Script script = data.GetScript(id);
    
                ProcessStartInfo psi = new ProcessStartInfo()
                {
                    FileName = script.Path,
                    RedirectStandardOutput = true,
                    RedirectStandardInput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };
    
                CurrentProcess = new Process();
                CurrentProcess.StartInfo = psi;
    
                OutputThread = new Thread(Output);
    
                CurrentProcess.Start();
                OutputThread.Start();
    
                ScriptOutputControl.SetTimerEnabled(true);
    
                litScript.Text = "<script type=\"text/javascript\" language=\"javascript\">ShowScriptModal();</script>";
    
                SetFocus("txtInput");
            }
    
            void Output()
            {
                while (ScriptRunning)
                {
                    var x = CurrentProcess.StandardOutput.Read();
                    if (x != -1)
                        ScriptOutputQueue.Enqueue((char)x);
                }
            }
    
            public void btnScriptInput_Click(object sender, EventArgs e)
            {
                string input = hiddenInput.Value.ToString();
    
                ScriptOutputControl.Input(input);
    
                foreach (char x in input.ToArray())
                {
                    if (CurrentProcess != null && !CurrentProcess.HasExited)
                    {
                        CurrentProcess.StandardInput.Write(x);
                    }
                    Thread.Sleep(1);
                }
            }
    
            protected void btnExit_Click(object sender, EventArgs e)
            {
                Reset();
            }
        }
    }
    
    // ====== ====== ====== ====== ====== ====== ====== ====== ====== ====== ======//
    
    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ScriptOutput.ascx.cs"
        Inherits="MITool.Controls.ScriptOutput" %>
    <asp:Label ID="lblStats" runat="server" Style="color: Red" />
    <br />
    <asp:UpdatePanel ID="OutputUpdatePanel" runat="server" ClientIDMode="Static">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
            <asp:AsyncPostBackTrigger ControlID="btnScriptInput" EventName="Click" />
        </Triggers>
        <ContentTemplate>
            <asp:Literal ID="litOutput" runat="server" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:Timer ID="UpdateTimer" Interval="100" runat="server" OnTick="UpdateTimer_Tick" Enabled="false" />
    
    // ====== ====== ====== ====== ====== ====== ====== ====== ====== ====== ======//
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Collections.Concurrent;
    using System.Diagnostics;
    
    namespace MITool.Controls
    {
        public partial class ScriptOutput : System.Web.UI.UserControl
        {
            string Output
            {
                get
                {
                    if (Session["Output"] != null)
                        return Session["Output"].ToString();
                    return string.Empty;
                }
                set
                {
                    Session["Output"] = value;
                }
            }
    
            ConcurrentQueue<char> ScriptOutputQueue
            {
                get
                {
                    return (ConcurrentQueue<char>)Session["ScriptOutputQueue"];
                }
                set
                {
                    Session["ScriptOutputQueue"] = value;
                }
            }
            Process CurrentProcess
            {
                get
                {
                    return (Process)Session["CurrentProcess"];
                }
                set
                {
                    Session["CurrentProcess"] = value;
                }
            }
            bool ScriptRunning
            {
                get
                {
                    if (CurrentProcess == null)
                        return false;
                    if (!CurrentProcess.HasExited || CurrentProcess.StandardOutput.Peek() != -1)
                        return true;
                    return false;
                }
            }
            bool OutputProcessing
            {
                get
                {
                    if (ScriptOutputQueue != null && ScriptOutputQueue.Count != 0)
                        return true;
                    return false;
                }
            }
    
            public void SetTimerEnabled(bool enabled)
            {
                UpdateTimer.Enabled = enabled;
            }
            public void ClearOutputText()
            {
                Output = string.Empty;
                litOutput.Text = Output;
            }
    
            protected void UpdateTimer_Tick(object sender, EventArgs e)
            {
                ProcessOutput();
    
                if (!ScriptRunning && !OutputProcessing)
                {
                    UpdateTimer.Enabled = false;
    
                    Output += "<br />// SCRIPT END //<br />";
                    litOutput.Text = Output;
                }
            }
    
            public void Input(string s) 
            {
                Output += "<br />// " + s + "<br />";
            }
    
            void ProcessOutput()
            {
                string s = string.Empty;
    
                while (ScriptOutputQueue != null && ScriptOutputQueue.Any())
                {
                    char x;
                    if (ScriptOutputQueue.TryDequeue(out x))
                    {
                        s += x;
                    }
                }
    
                if (s != string.Empty)
                {
                    s = Server.HtmlEncode(s);
                    s = s.Replace("\r\n", "<br />");
    
                    Output += s;
                }
    
                litOutput.Text = Output;
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
Basically, what I'm trying to create is a page of div tags, each has
I want to count how many characters a certain string has in PHP, but
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I have a jquery bug and I've been looking for hours now, I can't
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.