C# Output to Console

引用来自:http://stackoverflow.com/questions/472282/show-console-in-windows-application

       [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool AllocConsole();

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool FreeConsole();

        [DllImport("kernel32", SetLastError = true)]
        static extern bool AttachConsole(int dwProcessId);

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();

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

        /// <summary>
        /// 显示输出到命令行
        /// </summary>
        /// <param name="message"></param>
        private static void ShowOutputConsole(string message)
        {
            //Get a pointer to the forground window.  The idea here is that
            //IF the user is starting our application from an existing console
            //shell, that shell will be the uppermost window.  We'll get it
            //and attach to it
            IntPtr ptr = GetForegroundWindow();
            int u;
            GetWindowThreadProcessId(ptr, out u);
            Process process = Process.GetProcessById(u);
            //Is the uppermost window a cmd process?
            if (process.ProcessName == "cmd")    
                
            {
                AttachConsole(process.Id);
                //we have a console to attach to ..
                Console.WriteLine(message);
            }
        }

posted @ 2012-05-03 14:50  谷安  阅读(753)  评论(0编辑  收藏  举报