2012-02-24 108 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