Search code examples
c#.netconsole-applicationsystem.diagnostics

Console.KeyAvailable Fails When Starting a Process


Here's a snippet of code the works just fine. As I am simulating a long running process, any keystrokes are queued up. The Console.Available returns true and false just as the documentation indicates it should. Everything works great here:

while (true) {
   Console.WriteLine("Starting long task...");
   // Simulate some long task by sleeping 3 seconds
   System.Threading.Thread.Sleep(3000);
   Console.WriteLine("Long task is finished.");

   if (Console.KeyAvailable) 
      Console.WriteLine("A key is available: " + Console.ReadKey(false).Key);
   else
      Console.WriteLine("*** No Key available ***");
}

Here's the problem: When I substitute the Thread.Sleep() with code to create and run a real Process, the Console.KeyAvailable ceases to work. Console.KeyAvailable behaves erratically, usually returning false but sometimes returning true if I type enough keys fast enough.

Has anyone an explanation for this?

while (true) {
   LongRunningProcess("someFile.bin");

   if (Console.KeyAvailable) 
      Console.WriteLine("A key is available: " + Console.ReadKey(false).Key);
   else
      Console.WriteLine("*** No Key available ***");
}

private static bool LongRunningProcess(String filename) {
   ProcessStartInfo processStartInfo = new ProcessStartInfo("BlahBlahBlah.exe", filename);
   processStartInfo.UseShellExecute = false;
   processStartInfo.RedirectStandardError = true;

   Process p = new Process();
   p.StartInfo = processStartInfo;
   p.Start();

   StreamReader stdError = p.StandardError;

   int readResult = stdError.Read();

   p.Close();

   if (readResult != -1) // error was written to std error
      return false;

   return true;
} 

Solution

  • The started process shows a window that becomes the active window. Your console application only receives keyboard input while your console window is the active window. Try setting the CreateNoWindow property of the ProcessStartInfo to true.