在Winform動態啟動、控制台命令列的方法

來源:互聯網
上載者:User

需求
winForm 程式輸出類型為 windows 程式(不是命令列程式)
在運行時想輸入一些資訊編譯開發調試,如何?這一功能

解答:

AllocConsole、FreeConsole 這兩個 API 可以在任何時候調用和關閉 命令列。

代碼示範:
API 部分

複製代碼 代碼如下: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.Windows.Forms;

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.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);
}
}
}

代碼下載:(VS2008 如果其他版本VS請自行修改)
http://xiazai.jb51.net/201302/other/WinformShellConsole_VS08.rar

最後:

其實代碼很簡單,不過很適合在運行時輸出一些臨時調試資訊
用GUI畫圖的操作一般下斷點很容易影響Print 事件的情況
,有時候在客戶那裡程式問題在上開啟控制台輸出一些調試資訊看著比較方便;
而且控制太沒有線程限制的,所以使用起來要比單獨的日誌視窗方便、而且容易複製內容,還支援 paus 鍵;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.