C#控制台应用程序响应第二个命令?

时间:2018-06-27 22:11:39

标签: c# command console-application

我正在编写控制台应用程序“任务管理器”以学习更好的C#。

我有一个小问题。每次用户(我)键入不是命令的内容时,应用程序都应查找具有我键入的名称/文本的进程。

到目前为止,它仍然有效,但是每输入我的文字就会回复一次。

这是我的代码:

    static void Main(string[] args)
    {
        string s = "Console Task Manager v1.0.0";
        Console.WriteLine();
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.SetCursorPosition((Console.WindowWidth - s.Length) / 2, Console.CursorTop);
        Console.WriteLine(s);
        Console.WriteLine("Type 'exit' for close this application.");
        Console.WriteLine("\nPlease type the process what are you looking for:");

        while (Console.ReadLine() != "exit")
        {
            GetProcesses();
        }
    }

    static void GetProcesses()
    {
        Process[] processes = Process.GetProcessesByName(Console.ReadLine());

        foreach(Process process in processes)
        {
            Console.WriteLine("ID: " + process.Id + " | Name: " + process.ProcessName);
            //process.Kill();
        }
    }

为了更好地想象我的问题,我为该问题添加了屏幕截图。 Screenshot 谢谢您的帮助。

2 个答案:

答案 0 :(得分:4)

您遇到此问题是因为您在两个地方都有Console.ReadLine()。第一个Console.ReadLine()用于检查退出。第二个用于获取进程名称。然后第一个被再次调用,依此类推。

static void Main(string[] args)
{
    string s = "Console Task Manager v1.0.0";
    Console.WriteLine();
    Console.ForegroundColor = ConsoleColor.Cyan;
    Console.SetCursorPosition((Console.WindowWidth - s.Length) / 2, Console.CursorTop);
    Console.WriteLine(s);
    Console.WriteLine("Type 'exit' for close this application.");
    Console.WriteLine("\nPlease type the process what are you looking for:");

    while (Console.ReadLine() != "exit") // readline 1
    {
        GetProcesses();
    }
}

static void GetProcesses()
{
    Process[] processes = Process.GetProcessesByName(Console.ReadLine()); // readline 2

    foreach(Process process in processes)
    {
        Console.WriteLine("ID: " + process.Id + " | Name: " + process.ProcessName);
        //process.Kill();
    }
}

如果您查看程序流程,则如下所示:

readline 1(仅用于检查退出)
GetProcesses
readline 2-获取进程名称
GetProcesses返回
阅读专线1
GetProcesses
readline 2-获取进程名称
GetProcesses返回
...

一种解决方法是执行以下操作:

static void Main(string[] args)
{
    string s = "Console Task Manager v1.0.0";
    Console.WriteLine();
    Console.ForegroundColor = ConsoleColor.Cyan;
    Console.SetCursorPosition((Console.WindowWidth - s.Length) / 2, Console.CursorTop);
    Console.WriteLine(s);
    Console.WriteLine("Type 'exit' for close this application.");
    Console.WriteLine("\nPlease type the process what are you looking for:");

    string lastCommand = string.Empty;
    do
    {
        lastCommand = Console.ReadLine();
        if (lastCommand != "exit")
        {
            KillProcess(lastCommand);
        }
    } while (lastCommand != "exit");
}

static void KillProcess(string processName)
{
    Process[] processes = Process.GetProcessesByName(processName);

    foreach(Process process in processes)
    {
        Console.WriteLine("ID: " + process.Id + " | Name: " + process.ProcessName);
        //process.Kill();
    }
}

编辑: 如果要进一步扩展此功能并添加其他命令,则可以执行类似的操作,在此您可以使用新函数来解析该命令。

/// <summary>
/// Field that indicates whether or not the program should keep running.
/// </summary>
static bool keepRunning = true;

static void Main(string[] args)
{
  string s = "Console Task Manager v1.0.0";
  Console.WriteLine();
  Console.ForegroundColor = ConsoleColor.Cyan;
  Console.SetCursorPosition((Console.WindowWidth - s.Length) / 2, Console.CursorTop);
  Console.WriteLine(s);
  Console.WriteLine("Type 'exit' for close this application.");
  Console.WriteLine("\nPlease type the process what are you looking for:");

  do
  {
    string lastCommand = Console.ReadLine();
    ProcessCommand(lastCommand);
  } while (keepRunning);
}

/// <summary>
/// Processes a command we've received.
/// </summary>
/// <param name="command">The command that was entered.</param>
static void ProcessCommand(string command)
{
  if (string.IsNullOrEmpty(command))
  {
    return;
  }

  // A command might have one or more parameters, these will be separated
  // by spaces (i.e. "kill 12345").
  string[] commandParts = command.Split(' ');

  // Process each command we know about.
  if (commandParts[0] == "exit")
  {
    keepRunning = false;
  }
  else if (commandParts[0] == "kill")
  {
    // This command needs 1 parameter.
    if (commandParts.Length < 2)
    {
      Console.WriteLine("kill command requires process name or ID");
      return;
    }

    // Try checking if the second value can be parsed to an integer. If so
    // we'll assume it's the process ID to kill. Otherwise, we'll try to 
    // kill the process by that name.
    int id;
    if (int.TryParse(commandParts[1], out id))
    {
      KillProcessByID(id);
    }
    else
    {
      KillProcessByName(commandParts[1]);
    }
  }
  // More commands can be added here.

  // This isn't a known command.
  else
  {
    Console.WriteLine("Unknown command \"" + command + "\"");
  }
}

static void KillProcessByName(string processName)
{
  Process[] processes = Process.GetProcessesByName(processName);

  foreach (Process process in processes)
  {
    Console.WriteLine("ID: " + process.Id + " | Name: " + process.ProcessName);
    //process.Kill();
  }
}

static void KillProcessByID(int processID)
{
  Process process = Process.GetProcessById(processID);
  if (process != null)
  {
    Console.WriteLine("ID: " + process.Id + " | Name: " + process.ProcessName);
    //process.Kill();
  }
}

答案 1 :(得分:0)

这是因为您正在读取控制台2次。

Console.ReadLine()

等待用户交互。

读取一次并存储该值,然后检查它是否为命令,然后将其传递给您的方法以读取prozes。