先看一下這段啟動代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace WindowsService1
{
static class Program
{
/// <summary>
/// 應用程式的主進入點。
/// </summary>
static void Main()
{
Service1 s = new Service1();
if (Environment.UserInteractive)
{
s.DebugStart();
Console.ReadKey();
s.DebugStop();
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { s };
ServiceBase.Run(ServicesToRun);
}
}
}
}
關鍵就在對Environment.UserInteractive的判斷上,
請看MSDN上面的解釋:
擷取一個值,用以指示當前進程是否在使用者互動模式中運行。
UserInteractive 屬性為運行時無使用者介面的 Windows 進程或一個服務(如 IIS)報告 false。 如果此屬性為 false,請不要顯示模式對話方塊或訊息框,因為沒有用來與使用者進行互動的圖形化使用者介面。
http://msdn.microsoft.com/zh-cn/library/system.environment.userinteractive(v=VS.100).aspx
然後看一下Service1.cs中的代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.ServiceStart();
}
protected override void OnStop()
{
this.ServiceStop();
}
internal void DebugStart()
{
this.ServiceStart();
}
internal void DebugStop()
{
this.ServiceStop();
}
private void ServiceStart()
{
// TODO:
}
private void ServiceStop()
{
// TODO:
}
}
}
最後:更改Project的輸出類型
右擊該Project,點擊Properties,在Application標籤中,更改Output Type為Console Application。
OK啦,按F5試試