通过添加程序逻辑控制台 [英] Adding a Console via Program logic
问题描述
我有一个窗口服务。如果我开始从调试器我想与控制台输出(因为你不能运行一个服务)上运行。
I have a windows service. If I start it from the debugger I want to run with console output (since you can not run a service).
通常一个Windows服务被设置为具有WindowApplication作为项目类型和不具有窗口的入口点。因此,如果你想你需要将项目类型更改为ConsoleAppication控制台窗口中删除历久弥新控制台。
Usually a Windows Service is set to WindowApplication as project type and has no "window" entry point. Thus it removes the good old console.
。我想程序本身,而不是改变项目设置中做到这一点。
If you want a console window you need to change the project type to ConsoleAppication. I would like to do this within the program itself instead changing the Project settings.
这可能吗?
推荐答案
其实,程序启动,看它是否是作为服务运行与否,然后使用AllocConsole命令启动控制台时,您可以使用一个简单的检查。下面是示例代码。
Actually you can use a simple check when the program starts to see if it is running as a service or not and then use the AllocConsole command to start the console. Here is the sample code.
namespace TestService
{
static class Program
{
[DllImport("kernel32.dll")]
static extern bool AllocConsole();
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
if (!Environment.UserInteractive)
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
else
{
AllocConsole();
//Start Code that interfaces with console.
}
}
}
}
这篇关于通过添加程序逻辑控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!