標籤:winform style blog color os io for ar
需求
winForm 程式輸出類型為 windows 程式(不是命令列程式)
在運行時想輸入一些資訊編譯開發調試,如何?這一功能
解答:
AllocConsole、FreeConsole 這兩個 API 可以在任何時候調用和關閉 命令列。
代碼示範:
API 部分
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
public partial class NativeMethods {
/// <summary>
/// 啟動控制台
/// </summary>
/// <returns></returns>
[DllImport("kernel32.dll")]
public static extern bool AllocConsole();
/// <summary>
/// 釋放控制台
/// </summary>
/// <returns></returns>
[DllImport("kernel32.dll")]
public static extern bool FreeConsole();
}
}
啟動參數的實現
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// 應用程式的主進入點。
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
if(args.Length > 0 && args[0].ToLower() == "-c")
{//通過命令列 xxxx.exe -c 參數啟動,Console
//注意:不用 Main(string[] args)、System.Environment.GetCommandLineArgs(); 也可以取得命令列參數在任何地方
//啟動
NativeMethods.AllocConsole();
Console.WriteLine("控制台以啟動");
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
finally
{
//關閉 (如果在這個位置其實寫不寫都行了)
NativeMethods.FreeConsole();
}
}
}
}
程式實現
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOpenConsole_Click(object sender, EventArgs e)
{
//開啟控制台
NativeMethods.AllocConsole();
}
private void btnCloseConsole_Click(object sender, EventArgs e)
{
//關閉控制台
NativeMethods.FreeConsole();
}
private void btnOut_Click(object sender, EventArgs e)
{
//類比輸出
Console.WriteLine(textBox1.Text);
}
}
}