目前,我正在努力使用一个可以通过命令提示符或通过Windows窗体应用程序使用的应用程序。此应用程序也将用作服务。由于显而易见的原因(如重写代码并跟上两个应用程序的更改),我只想创建一个应用程序。
目前我正在使用以下方法实现这一目标(我已将所有调试代码包括在内,以防有人提出任何具体建议)...
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyApplicationSpace
{
static class Program
{
#region Private class APIs
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AttachConsole(int pid);
[DllImport("kernel32")]
private static extern bool AllocConsole();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FreeConsole();
#endregion
#region Constructor
/// <summary>
/// The main entry point for the application.
/// </summary>
private static void Main(string[] args)
{
if (args.Contains("-service"))
{
ServiceBase[] servicesToRun;
servicesToRun = new ServiceBase[]
{
new MyServiceClass()
};
if (Environment.UserInteractive)
{
if (!AttachConsole(-1)) AllocConsole();
RunInteractive(servicesToRun);
FreeConsole();
SendKeys.SendWait("{ENTER}");
}
else
ServiceBase.Run(servicesToRun);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
#endregion
#region Private class functions
private static void RunInteractive(ServiceBase[] servicesToRun)
{
Console.WriteLine("Services running in interactive mode.");
Console.WriteLine();
MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (ServiceBase service in servicesToRun)
{
Console.Write("Starting {0}...", service.ServiceName);
onStartMethod.Invoke(service, new object[] { new string[] { } });
Console.Write("Started");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Press any key to stop the services and end the process...");
Console.WriteLine("BEFORE ReadKey");
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "error.log", "BEFORE ReadKey");
try
{
Console.ReadKey();
}
catch (Exception ex)
{
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "error.log", ex.Message);
}
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "error.log", "AFTER ReadKey");
Console.WriteLine("AFTER ReadKey");
Console.WriteLine();
Console.WriteLine("Continuing...");
MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
Console.WriteLine("onStopMethod is null = " + (onStopMethod == null));
Console.WriteLine("Foreach service in service to run count:" + servicesToRun.Count());
foreach (ServiceBase service in servicesToRun)
{
Console.Write("Stopping {0}...", service.ServiceName);
onStopMethod.Invoke(service, null);
Console.WriteLine("Stopped");
}
Console.WriteLine("All services stopped.");
// Keep the console alive for a second to allow the user to see the message.
Thread.Sleep(1000);
}
#endregion
}
}
当我尝试拨打Console.ReadKey()
时会出现问题。程序似乎挂起或在某种程度上退出。例如,当我从命令提示符运行它时,它按预期运行,然后显示&#34;按任意键停止服务并结束进程...&#34;以及#34;在ReadKey&#34;之前。然后,一旦我点击[ENTER]
控制台就回到默认的命令提示符。但由于某种原因,应用程序仍显示为在任务管理器中运行。似乎它被挂断了。
如果我将应用程序类型更改为console application
,一切都按预期工作,看起来很棒。但我需要将其构建为windows application
。我认为使用AttachConsole(-1)
的问题与将其构建为控制台应用程序不同。
答案 0 :(得分:0)
这归功于汉斯。我不确定他为什么删除了他的答案,但我希望他不会。
基本上命令进程和我的应用程序正在争夺命令窗口(他说它比我更优雅)。
他建议我可以做两件事之一。
创建一个与我的应用"my app name.com"
分开的小应用"my app name.exe"
,让它自己创建一个新的命令窗口来启动服务。
使用Windows start
命令运行应用程序,而不是尝试正常运行它。
我选择使用梯形法。使用等待开关,它会强制命令处理器等待应用程序完成,直到它再次尝试抓住按键。运行start
时请注意第三个参数。它是""
两个双引号,用于在/wait
参数之后传递空白参数。这是必要的,以便在您运行的应用程序之后传递params。
C:\“我的app name.exe” - 服务
C:\ start / wait“”“我的app name.exe” - service