原文地址:http://www.cnblogs.com/seayxu/p/4643306.html
在Winform程序中有时候调试会通过Console.Write()方式输出一些信息,这些信息是在Visual Studio的输出窗口显示。所以就会想,能不能调用系统的Cmd窗口输出呢,经过一番查阅,发现是可以的,现在就把方法写下了:
主要用到的是win32 API函数实现的:
1 [DllImport("kernel32.dll")]
2 static extern bool FreeConsole();
3 [DllImport("kernel32.dll")]
4 public static extern bool AllocConsole();
[DllImport("kernel32.dll")]
2 static extern bool FreeConsole();
3 [DllImport("kernel32.dll")]
4 public static extern bool AllocConsole();
在Program.cs文件中调用方法即可,完整代码:
1 using System;
2 using System.Collections.Generic;
3 using System.Windows.Forms;
4 using System.Runtime.InteropServices;
5
6 namespace XY.WinformDebug
7 {
8 static class Program
9 {
10 [DllImport("kernel32.dll")]
11 static extern bool FreeConsole();
12 [DllImport("kernel32.dll")]
13 public static extern bool AllocConsole();
14 /// <summary>
15 /// 应用程序的主入口点。
16 /// </summary>
17 [STAThread]
18 static void Main()
19 {
20 AllocConsole();//调用系统API,调用控制台窗口
21 Application.EnableVisualStyles();
22 Application.SetCompatibleTextRenderingDefault(false);
23 Application.Run(new FrmMain());
24 FreeConsole();//释放控制台
25 }
26 }
27 }
1 using System;
2 using System.Collections.Generic;
3 using System.Windows.Forms;
4 using System.Runtime.InteropServices;
5
6 namespace XY.WinformDebug
7 {
8 static class Program
9 {
10 [DllImport("kernel32.dll")]
11 static extern bool FreeConsole();
12 [DllImport("kernel32.dll")]
13 public static extern bool AllocConsole();
14 /// <summary>
15 /// 应用程序的主入口点。
16 /// </summary>
17 [STAThread]
18 static void Main()
19 {
20 AllocConsole();//调用系统API,调用控制台窗口
21 Application.EnableVisualStyles();
22 Application.SetCompatibleTextRenderingDefault(false);
23 Application.Run(new FrmMain());
24 FreeConsole();//释放控制台
25 }
26 }
27 }
*****************************************************************
其实不需要这么费劲,打开一个Windows Form的工程的设置界面,在Output type选择Console Application,这样就会默认出现一个黑窗口,调用 Console.WriteLine() 函数即可正常输入输出数据,对于调试比较方便,不需要的时候改成Windows Application即可 。