2012-02-24 75 views
0

我在一个应用程序中运行窗体应用程序和控制台应用程序。窗体和控制台

我怎样才能运行窗体应用程序,并保持控制台关闭,直到我点击窗体上的按钮?

回答

0

您需要调用几个win32app调用,特别是allocconsole。这里有一个msdn的帖子和一些示例代码。

0

你需要做一个小的P/Invoke:

添加适当的方法:

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 StackOverflow.Extensions; 
using System.Runtime.InteropServices; 
using System.IO; 
using Microsoft.Win32.SafeHandles; 

namespace StackOverflow 
{ 
    public partial class FormMain : Form 
    { 
     [DllImport("kernel32.dll", 
      EntryPoint = "GetStdHandle", 
      SetLastError = true, 
      CharSet = CharSet.Auto, 
      CallingConvention = CallingConvention.StdCall)] 
     private static extern IntPtr GetStdHandle(int nStdHandle); 

     [DllImport("kernel32.dll", 
      EntryPoint = "AllocConsole", 
      SetLastError = true, 
      CharSet = CharSet.Auto, 
      CallingConvention = CallingConvention.StdCall)] 
     private static extern int AllocConsole(); 

     // Some constants 
     private const int STD_OUTPUT_HANDLE = -11; 
     private const int MY_CODE_PAGE = 437; 

     public FormMain() 
     { 
      InitializeComponent(); 
     } 

     public void PrepareConsole() 
     { 
      AllocConsole(); 
      IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE); 
      SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true); 
      FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write); 
      Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE); 
      StreamWriter standardOutput = new StreamWriter(fileStream, encoding); 
      standardOutput.AutoFlush = true; 
      Console.SetOut(standardOutput); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      // Console was not visible before this button click 
      Console.WriteLine("This text is written to the console that just popped up."); 

      MessageBox.Show("But we're still in a Windows Form application."); 
     } 
    } 
} 
+0

我一直想知道为什么的CreateFile使用SafeFileHandle有返回值,但GetStdHandle没有。 – Rahly 2014-01-06 02:06:26

+0

它一直在为我工作,但突然停下来,不知道为什么。其他人是否有反馈? – WSK 2016-08-18 16:41:49