Click here to Skip to main content
15,896,606 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 631.2K   27.8K   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
{
    public class WindowFinder
    {
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
        [DllImport("user32.dll")]
        static extern bool EnumDesktopWindows(IntPtr hDesktop,
           EnumWindowsProc lpfn, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

        private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

        public WindowFinder()
        {
            ewp = new EnumWindowsProc(EnumWindowFunction);
        }

        public IntPtr FindWindowHandleByProcessId(int processId)
        {
            pid = processId;
            EnumDesktopWindows(IntPtr.Zero, ewp, IntPtr.Zero);
            return windowHandle;
        }

        private EnumWindowsProc ewp;

        private bool EnumWindowFunction(IntPtr hWnd, IntPtr lParam)
        {
            //  Is it the right window?
            uint pID = 0;
            GetWindowThreadProcessId(hWnd, out pID);
            if (pID == pid)
            {
                windowHandle = hWnd;
                return false;
            }
            return true;
        }

        IntPtr windowHandle = IntPtr.Zero;
        int pid = 0;
    }
}

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