在C#WinForms程序

时间:2016-01-30 02:11:14

标签: c# winforms console command-line-interface pty

我想在C#WinForms应用程序中构建一个终端,用于通过串行端口,网络上的终端或任何其他类型的命令/响应机制进行通信。

我认为最简单的方法是打开Windows控制台并将stdin,stdout和stderr流重定向到我的程序中的TextStreams,但我找不到明显的方法来执行此操作。我不想使用System.Console并将其与其他错误/调试消息混淆。

如果我可以将控制台作为WinForm的控件嵌入,那就更好了。

在没有任何第三方库或大量编码的情况下,这些解决方案是否可行?

谢谢!

1 个答案:

答案 0 :(得分:1)

使用此类从WinForms访问控制台。 您需要分配一个控制台并将其保存到变量中以供以后操作。我在下面的示例代码中包含了一些示例代码。然后,您可以调用Console.WriteLine(“”)方法将文本发送到窗口。希望这有帮助!

public class ConsoleHelper
{
    public const int MF_BYCOMMAND = 0x00000000;
    public const int SC_CLOSE = 0xF060;

    /// <summary>
    /// Allocates a new console for current process.
    /// </summary>
    [DllImport("kernel32.dll")]
    public static extern Boolean AllocConsole();

    /// <summary>
    /// Frees the console.
    /// </summary>
    [DllImport("kernel32.dll")]
    public static extern Boolean FreeConsole();

    [DllImport("kernel32.dll")]
    public static extern IntPtr GetConsoleWindow();

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    [DllImport("user32.dll")]
    public static extern int DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);

    [DllImport("user32.dll")]
    public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

    public const int SW_HIDE = 0;
    public const int SW_SHOW = 5;
}

以下是一个快速演示:

    void OpenSerialConnection(int portnumber, System.Windows.Forms.NotifyIcon TrayIcon)
    {
        //Get console window
        handle = ConsoleHelper.GetConsoleWindow();
        if (handle.ToInt32() == 0)
        {
            //Create the console window
            ConsoleHelper.AllocConsole();
        }
        handle = ConsoleHelper.GetConsoleWindow();

        //Show console window
        ConsoleHelper.ShowWindow(handle, ConsoleHelper.SW_SHOW);

        //Remove close button from console window (can only be closed from code now)
        ConsoleHelper.DeleteMenu(ConsoleHelper.GetSystemMenu(ConsoleHelper.GetConsoleWindow(), false), ConsoleHelper.SC_CLOSE, ConsoleHelper.MF_BYCOMMAND);
        if (!serialPort1.IsOpen)
        {
            try
            {
                serialPort1.PortName = "COM" + portnumber.ToString();
                serialPort1.BaudRate = Form1.BaudRate;
                serialPort1.Open();
            }
            catch (Exception error)
            {
                TrayIcon.ShowBalloonTip(3000, "Error in " + error.Source.ToString(), "The program encountered an error while trying to open the serial connection. This may be due to closing the program prematurely. Try unplugging your board and restarting the program!", System.Windows.Forms.ToolTipIcon.Error);
                //Hide console window
                ConsoleHelper.ShowWindow(handle, ConsoleHelper.SW_HIDE);
            }
        }
        Console.Clear();
        Console.BackgroundColor = ConsoleColor.Gray;
        Console.ForegroundColor = ConsoleColor.Black;
        Console.WriteLine("====CONSOLE OPENED ON (COM PORT " + portnumber.ToString() + ")=======");
        Console.WriteLine("===========BAUD RATE: " + Form1.BaudRate.ToString() + "=============");
        Console.BackgroundColor = ConsoleColor.Black;
        Console.ForegroundColor = ConsoleColor.White;
    }