【问题标题】:What is the Console path in C#?C# 中的控制台路径是什么?
【发布时间】:2012-12-14 12:59:37
【问题描述】:

我正在尝试在从单击按钮启动的控制台中显示文本。我想我需要输入我放置问号 Process.Start("????") 的控制台路径。如何找到控制台路径?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Process.Start("????");
        Console.WriteLine("Adam");
        Console.Read();
    }
}

【问题讨论】:

  • 这不是你认为的那样。 Console.WriteLine 不会写入以Process.Start 开头的命令行进程。相反,它将写入您的应用程序的控制台 - 因为您有一个 WinForms 应用程序,所以在您的情况下不存在该控制台。请在此处说明您要达到的目标。
  • 好的,谢谢您的信息。我想我需要多读一点。我是否需要保存控制台操作(在控制台应用程序下/使用控制台应用程序),然后通过单击按钮从 Windows 窗体应用程序访问该操作/进程?
  • 你真正想要实现什么?你只是想要一个方便的控制台来写一堆消息吗?

标签: c# path console-application


【解决方案1】:

这是一个很好的例子:http://cboard.cprogramming.com/csharp-programming/130369-command-prompt-use-within-csharp-class-file.html#post973331

代码:

string returnvalue = "";

// Starts the new process as command prompt
ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
info.UseShellExecute = false;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
// Makes it so the command prompt window does appear
info.CreateNoWindow = true;

using (Process process = Process.Start(info))
{
    StreamWriter sw = process.StandardInput;
    StreamReader sr = process.StandardOutput;

    // This for loop could be used if you had a string[] commands where each string in commands
    // is it's own command to write to the prompt. I chose to hardcode mine in.
    //foreach (string command in commands)
    //{
    //    sw.WriteLine(command);
    //}
    sw.WriteLine("cd " + processPath);
    sw.WriteLine("perl process.pl");

    sw.Close();
    returnvalue = sr.ReadToEnd();
}

return returnvalue;

【讨论】:

    【解决方案2】:

    您需要做的是从 Windows API 中获取控制台。这将创建一个可以输出和读取等的控制台应用程序的新实例。

    public partial class Form1 : Form
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern int AllocConsole();
    
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern int FreeConsole();
    
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            int alloc = AllocConsole(); // Grab a new console to write to
            if (alloc != 1)
            {
                MessageBox.Show("Failed");
                return;
                }
            Console.WriteLine("test");
    
            Console.WriteLine("Adam");
            string input = Console.ReadLine();
            Console.WriteLine(input);
            // Do other funky stuff
    
            // When done
            FreeConsole();
        }
    }
    

    【讨论】:

      【解决方案3】:

      您需要执行应用程序cmd.exe。但是使用 Controle.WriteLine 不会写入该控制台,Console.ReadLine 不会从该控制台读取。您必须重定向进程的输入和输出流才能与启动的控制台应用程序交互。

      【讨论】:

        【解决方案4】:

        你应该有两个项目。第一个是您的 Windows 应用程序,具有所有功能,另一个应该是类型为“控制台应用程序”的项目。然后你应该在按钮的点击事件中执行第二个项目(你的控制台应用程序.exe)的输出。

        问题是你没有办法这样称呼“Console.WriteLine”。简直是行不通。我的建议是使用 .NET Remoting 在两个不同的项目之间做人员。

        .NET 远程 IPC:

        http://www.codeguru.com/csharp/csharp/cs_syntax/remoting/article.php/c9251/NET-Remoting-Using-a-New-IPC-Channel.htm

        希望对你有帮助!

        【讨论】:

          【解决方案5】:

          这是一个包装 AllocConsole() 的类:

          /// <summary>Simple class to allow creation and destruction of Consoles.</summary>
          
          public static class ConsoleManager
          {
              #region public static Methods
          
              /// <summary>
              /// Creates a console output window, if one doesn't already exist.
              /// This window will receive all outputs from System.Console.Write()
              /// </summary>
              /// <returns>
              /// 0 if successful, else the Windows API error code from Marshal.GetLastWin32Error()
              /// </returns>
              /// <remarks>See the AllocConsole() function in the Windows API for full details.</remarks>
          
              public static int Create()
              {
                  if (AllocConsole())
                  {
                      return 0;
                  }
                  else
                  {
                      return Marshal.GetLastWin32Error();
                  }
              }
          
              /// <summary>
              /// Destroys the console window, if it exists.
              /// </summary>
              /// <returns>
              /// 0 if successful, else the Windows API error code from Marshal.GetLastWin32Error()
              /// </returns>
              /// <remarks>See the FreeConsole() function in the Windows API for full details.</remarks>
          
              public static int Destroy()
              {
                  if (FreeConsole())
                  {
                      return 0;
                  }
                  else
                  {
                      return Marshal.GetLastWin32Error();
                  }
              }
          
              #endregion  // public static Methods
          
              #region Private PInvokes
          
              [SuppressMessage( "Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage" ), SuppressUnmanagedCodeSecurity]
              [DllImport("kernel32.dll",SetLastError=true)]
              [return: MarshalAs( UnmanagedType.Bool )]
              static extern bool AllocConsole();
          
          
              [SuppressMessage( "Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage" ), SuppressUnmanagedCodeSecurity]
              [DllImport("kernel32.dll",SetLastError=true)]
              [return: MarshalAs( UnmanagedType.Bool )]
              static extern bool FreeConsole();
          
              #endregion  // Private PInvokes
          }
          

          只需调用 ConsoleManager.Create(),然后您应该可以执行 Console.WriteLine()。

          【讨论】:

          • 好的,我正在编辑我的回复,希望对您有所帮助!
          猜你喜欢
          • 2011-05-22
          • 2010-11-20
          • 2019-06-13
          • 2023-03-22
          • 2011-06-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多