【问题标题】:How do I include a console in Winforms?如何在 Winforms 中包含控制台?
【发布时间】:2010-10-12 17:05:59
【问题描述】:

我想在 Winform 中嵌入一个控制台窗口。有没有办法做到这一点?

【问题讨论】:

    标签: c# winforms console


    【解决方案1】:

    你需要做的就是调用windows API函数AllocConsloe然后使用普通的控制台类这里是表单代码

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

    【讨论】:

    • @rerun,怎么回事,它找不到 Kernal32.dll?这是一个 x86 系统。
    • @rerun,一定是我将其设置为控制台应用程序,而不是 winforms 应用程序。我假设 Form1_Load 应该在表单加载时运行,这是正确的吗?如何让它运行?。
    • 只需创建一个带有 1 个表单的 winforms 应用程序,然后双击该表单,它将为您创建一个 form_load,您可以在任何地方调用 allocconsle,因为只有一个控制台可以与一个进程关联。
    • 哦,您希望控制台在窗口中。您可以编写自己的输入和管道输入到标准输出和标准输入。或者你可以嵌入 powershell 但没有控制。
    • “我想在 Winform 中嵌入一个控制台窗口” - 很清楚。
    【解决方案2】:

    哦!您希望控制台在窗口中。您可以编写自己的输入和管道输入到标准输出和标准输入。或者你可以嵌入 powershell 但没有控制。 – rerun 2010 年 10 月 12 日 19:49

    【讨论】:

    • 为什么这个答案(唯一一个真正的答案)不在顶部?
    【解决方案3】:

    您基本上可以通过以下方式做到这一点:

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

    您需要为此直接调用 API(您需要 SetParent 和 SetWindowPos)。这是一篇关于如何通过示例进行操作的文章:

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

    【讨论】:

      猜你喜欢
      • 2011-11-20
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 2013-02-21
      • 2017-11-13
      • 2021-09-11
      • 2011-04-13
      • 1970-01-01
      相关资源
      最近更新 更多