Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / C#

Embedding a Console in a C# Application

Rate me:
Please Sign up or sign in to vote.
4.91/5 (151 votes)
21 Mar 2015MIT4 min read 622.1K   27.7K   403  
Embed a functional console window in a C# application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleControl
{
    /// <summary>
    /// Provides additional functionality in the vein of SendKeys.
    /// </summary>
    public class SendKeysEx
    {
        /// <summary>The GetForegroundWindow function returns a handle to the foreground window.</summary>
        [DllImport("user32.dll")]
        internal static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        internal static extern bool SetForegroundWindow(IntPtr hWnd);

        /// <summary>
        /// Sends the keys.
        /// </summary>
        /// <param name="keys">The keys.</param>
        public static void SendKeys(IntPtr windowHandle, string keys)
        {
            //  Get the foreground window.
            IntPtr foregroundWindow = GetForegroundWindow();

            //  Set the specified window as the foreground window.
            SetForegroundWindow(windowHandle);

            //  Send the keys.
            System.Windows.Forms.SendKeys.Send(keys);

            //  Restore the window handle.
            SetForegroundWindow(foregroundWindow);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer
United Kingdom United Kingdom
Follow my blog at www.dwmkerr.com and find out about my charity at www.childrenshomesnepal.org.

Comments and Discussions