【问题标题】:Console.KeyAvailable Fails When Starting a Process启动进程时 Console.KeyAvailable 失败
【发布时间】:2016-10-20 22:25:33
【问题描述】:

这是一个运行良好的代码的 sn-p。当我模拟一个长时间运行的过程时,任何击键都会排队。 Console.Available 返回 true 和 false,正如文档所表明的那样。这里一切正常:

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 ***");
}

问题是:当我用代码替换Thread.Sleep() 以创建和运行真正的Process 时,Console.KeyAvailable 停止工作。 Console.KeyAvailable 行为不稳定,通常返回 false,但如果我足够快地键入足够多的键,有时会返回 true。

有人对此有解释吗?

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;
} 

【问题讨论】:

    标签: c# .net console-application system.diagnostics


    【解决方案1】:

    启动的进程显示一个成为活动窗口的窗口。您的控制台应用程序仅在您的控制台窗口是活动窗口时接收键盘输入。尝试将ProcessStartInfo 的CreateNoWindow 属性设置为true。

    【讨论】:

      猜你喜欢
      • 2015-04-16
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2014-05-06
      • 2017-12-27
      • 2015-01-14
      • 1970-01-01
      • 2014-11-02
      相关资源
      最近更新 更多