问题
Is it possible to add a console to a form based C# application ? Currently when I do something like
Console.WriteLine("testing");
It appears in output window of the VS2010. I want to know if its possible to attach a console to my windows form application.So that the output appears in the console.
EDIT: Looks like my first question was a bit misleading and it did not exactly specify what I wanted to accomplish. I just added a console to my application using
[DllImport("kernel32")]
static extern int AllocConsole();
However what I really want is the output of log4net console appender to be displayed in that console which is not happening. The xml for my appender is
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="INFO" />
<foreColor value="White" />
<backColor value="Red, HighIntensity" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%class %date - %message %newline" />
</layout>
</appender>
now when I go like
log.info("Some log");
It still does not display it in the newly added console window. Any suggestions on how i could do that ?
回答1:
Just make your project a console application and create/show a form from the console application rather than the other way around.
回答2:
Just to throw it out there, be sure that you AllocConsole()
before you load your log4net configuration. I tried doing something similar to what your question asks, and had the same problem before moving my call to AllocConsole
. Once I moved it, log4net automatically wrote to the console that I allocated.
Essentially ... (and remember to do all your regular error checking not included here) ...
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace SampleApp
{
class Program
{
[DllImport("kernel32.dll", SetLastError=true, CallingConvention=CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AllocConsole();
[DllImport("kernel32.dll", SetLastError=true, CallingConvention=CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeConsole();
[STAThread]
private static void Main(string[] args)
{
// (1) Make sure we have a console to use.
Program.AllocConsole();
try {
// (2) Tell log4net to configure itself according to our app.config data.
log4net.Config.XmlConfigurator.Configure();
// (3) Usual WinForms startup code here.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new SampleApp.Form1());
} catch ( Exception ) {
// WAT!
}
// (4) Remember to release the console before we exit.
Program.FreeConsole();
}
}
}
Not 100% sure why it makes a difference as to when the console is allocated, but this did fix the problem for me.
来源:https://stackoverflow.com/questions/14863282/adding-console-appender-to-a-windows-form-in-log4net