代码之家  ›  专栏  ›  技术社区  ›  Arlen Beiler

如何在WinForms中包含控制台?

  •  7
  • Arlen Beiler  · 技术社区  · 14 年前

    我希望在WinForm中嵌入一个控制台窗口。有什么办法吗?

    3 回复  |  直到 10 年前
        1
  •  8
  •   svick Raja Nadar    13 年前

    您只需要调用Windows API函数alloconsloe,然后使用普通的控制台类,这里是表单代码

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    
    namespace waTest
    {
        public partial class Form1 : Form
        {
            [DllImport("Kernel32.dll")]
            static extern Boolean AllocConsole( );
    
            public Form1( )
            {
                InitializeComponent();
            }
    
            private void Form1_Load( object sender, EventArgs e )
            {
                if ( !AllocConsole() )
                     MessageBox.Show("Failed");
                Console.WriteLine("test");
                string input = Console.ReadLine();
                MessageBox.Show(input);
            }
        }
    }
    
        2
  •  3
  •   Community CDub    8 年前

    哦!您希望控制台在窗口中。您可以编写自己的和管道输入到和来自stdout和stdin。或者您可以嵌入PowerShell,但没有烘焙控制。 rerun 10月12日19:49

        3
  •  2
  •   steinar Justin CI    14 年前

    基本上可以通过以下方式完成:

    1. 创建命令进程
    2. 将该进程的父进程设置为窗体(例如某些面板)
    3. 插入事件以在需要时调整大小
    4. 当主进程不再需要cmd进程时,终止该进程。

    您需要为此直接调用API(您需要setparent和setwindowpos)。下面是一篇关于如何通过示例实现这一点的文章:

    http://www.geekpedia.com/tutorial230_Capturing-Applications-in-a-Form-with-API-Calls.html