在调试winform程序时,经常使用Console类(用来替代Debug类)来写入IDE的输出窗口内容
通过使用kernel32.dll中的AllocConsole(用来附加到winform)函数以及与其匹配的FreeConsole(用来释放)函数让一个Console窗口附加到winform进程中。
这不仅限于调试,还有很多地方经常使用到这种方式
使用的例子:
using System;
using System.Windows.Forms;
namespace FormWithConsole
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
#if DEBUG
NativeMethods.AllocConsole();
Console.WriteLine("Debug Console");
#endif
Application.Run(new FormMain());
#if DEBUG
NativeMethods.FreeConsole();
#endif
}
}
}
下面的类包含了附加Console 和释放Console进程的方法
using System;
using System.Runtime.InteropServices;
namespace FormWithConsole
{
internal static class NativeMethods
{
// http://msdn.microsoft.com/en-us/library/ms681944(VS.85).aspx
/// <summary>
/// Allocates a new console for the calling process.
/// </summary>
/// <returns>nonzero if the function succeeds; otherwise, zero.</returns>
/// <remarks>
/// A process can be associated with only one console,
/// so the function fails if the calling process already has a console.
/// </remarks>
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern int AllocConsole();
// http://msdn.microsoft.com/en-us/library/ms683150(VS.85).aspx
/// <summary>
/// Detaches the calling process from its console.
/// </summary>
/// <returns>nonzero if the function succeeds; otherwise, zero.</returns>
/// <remarks>
/// If the calling process is not already attached to a console,
/// the error code returned is ERROR_INVALID_PARAMETER (87).
/// </remarks>
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern int FreeConsole();
}
}
原文地址:https://www.codeproject.com/Tips/68979/Attaching-a-Console-to-a-WinForms-application