由於項目裡涉及到與其他系統的介面資料傳遞,所以採取了建立Windows服務的方式來同步介面資料。內容很簡單,之所以把他記下來,是因為加深下自己的影響,也留個備份。
我們直接就上步驟吧:
第一,我們建立一個叫MyService的Windows程式。之後我們把Service1改名為MyService。
第二,聲明一個線程, private Thread thd;;同時在MyService的OnStart方法裡加入以下測試代碼:
if (thd == null || thd.ThreadState != System.Threading.ThreadState.Running)
{
thd = new Thread(new ThreadStart(RunApp));
thd.Start();
}
第三,加入以下方法代碼,代碼主要是實現尋找進程devenv.exe寫入到記錄檔裡面。
public void RunApp()
{
while (true)
{
int i = 0;
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if (p.ProcessName == "devenv")
{
LogLocation = System.Windows.Forms.Application.StartupPath + "\\" + "log";
LogMsg("測試", "找到進程devenv.exe");
}
}
}
Thread.Sleep(1000);
}
public static string LogLocation = "";
public static bool LogMsg(string ID, DateTime LogDate, string Msg)
{
try
{
if (ID == null || ID.Trim() == "")
return false;
if (LogLocation == "")
return false;
string path = LogLocation + "\\" + ID + "\\" + LogDate.ToString("yyyyMM");
string file = path + "\\" + LogDate.ToString("yyyyMMdd") + ".txt";
if (!System.IO.Directory.Exists(path))
System.IO.Directory.CreateDirectory(path);
if (!System.IO.File.Exists(file))
System.IO.File.Create(file).Close();
System.IO.StreamWriter sw = new System.IO.StreamWriter(file, true);
sw.WriteLine(FormatStr(Msg));
sw.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
private static string FormatStr(string msg)
{
return "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + msg;
}
public static bool LogMsg(string ID, string Msg)
{
return LogMsg(ID, DateTime.Now, Msg);
}
第四,在OnStop方法裡寫入以下代碼:
if (thd != null)
{
thd.Abort();
thd = null;
}
我們的這個服務代碼就已經寫完了,接下來我們要做的工作就是註冊該服務。
第五,點擊MyService.cd查看設計器,再點加右鍵會出現添加安裝程式。點擊以後會出現serviceProcessInstaller1和serviceInstaller1兩個組件。把serviceInstaller1的serviceName改成MyService,這裡有兩個地方需要注意.一個是StartType,有三種選擇自動,手動,禁用.如果想要自動啟動,那麼遍選擇Automatic即可.另一個需要注意的屬性是Account,選擇使用者,一般情況下,我們選擇Local System即可.。在Program.cs檔案中有段用於啟動服務,的代碼:
static void Main()
{
ServiceBase[] ServicesToRun;
// 同一進程中可以運行多個使用者服務。若要將
// 另一個服務添加到此進程中,請更改下行以
// 建立另一個服務物件。例如,
//
// ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
//
ServicesToRun = new ServiceBase[] { new MyService() };
ServiceBase.Run(ServicesToRun);
}
產生該解決方案。
第六,安裝服務,開啟Visual Studio 2005 命令提示,切換到你程式bin\Debug目錄下,輸入installutil MyService.exe,之後提示安裝成功。我們可以到我們服務裡去找剛才我們註冊的服務了,找到之後啟動它,那麼在進程裡就能找到MyService.exe這個進程了。到\bin\Debug目錄下,找是否有個log檔案裡存著今日的文字檔。
第七,卸載服務,切換到你程式bin\Debug目錄下,輸入installutil /u MyService.exe,就行了。
第八,調試服務,啟動Microsoft Visual Studio 2005的調試,同時啟動調試-》附加到進程,點擊顯示所有使用者進程,找到叫MyService.exe的進程,點加附加,我們就可以在我們的解決方案裡設定斷點調試了。over!謝謝!