views:

57

answers:

2

I would like to have a console window embedded in a Winform. Is there any way to do this?

+1  A: 

All you need to do is call the windows API function AllocConsloe then use the normal console class here is the form code

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
@rerun, what is the deal, it can't find Kernal32.dll? This is an x86 system.
Arlen Beiler
@rerun, must be that I had set this as a console app, not a winforms app. I assume Form1_Load is supposed to run when the form loads, is this correct? How do I get it to run?.
Arlen Beiler
Just create a winforms app with 1 form and double click on the form and it will create you a form_load you can however call allocconsle anywhere since only one console can be associated with a process.
rerun
How do I add the winform controls? I did say embedded in a form.
Arlen Beiler
Oh you want the console in the window. You can write your own and pipe input to and from stdout and stdin. Or you can imbed powershell but there is no baked in control.
rerun
A: 

You can do this basically by:

  1. Creating the cmd process
  2. Setting the parent of that process to be the form (or some panel for example)
  3. Plug in the events to resize when needed
  4. Kill the process when the main process doesn't need the cmd process anymore.

You need to call the API directly for this (you need SetParent and SetWindowPos). Here is an article on how to do it with examples:

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

steinar