C#在winform中调用系统控制台输出

原文地址: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即可 。

 

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值