在做好一個(gè)WPF的程序后桶至,有時(shí)候想讓它的部分功能以服務(wù)的形式安裝到Windows系統(tǒng)中狡相,然后以Windows服務(wù)的方式運(yùn)行后专,而圖形界面僅作該服務(wù)的配置用途。在此記錄一下開發(fā)的步驟以備忘美浦。
- 新建一個(gè)WPF的App弦赖,其實(shí)WinForm類之類的大同小異,為了調(diào)試的方便浦辨,我一般先以普通的App的方式建議項(xiàng)目蹬竖,然后把所有的配置功能等全做好,測試好流酬,把功能部分全完成币厕。
-
一切就緒好,開始來把這個(gè)WPF的App改造使之能支持Windows服務(wù)模式運(yùn)行:
2.1 在解決方案瀏覽器的項(xiàng)目標(biāo)題上右擊后依次選“添加Add”芽腾、“新項(xiàng)目New Item”:
圖1. 開始添加Windows服務(wù)相關(guān)內(nèi)容
2.2 如下圖的步驟操作旦装,第三步給添加的Windows服務(wù)取一個(gè)名字(這里以這個(gè)ServiceWatchdogSwitch為例):
圖2. 添加Windows服務(wù)
2.3 在解決方案瀏覽器里雙擊上面一步添加的服務(wù)ServiceWatchdogSwitch.cs,在屬性窗口配置好服務(wù)的名稱(ServiceName屬性)摊滔,接下來在打開的設(shè)計(jì)視圖空白處點(diǎn)右鍵后在彈出菜單中選“添加安裝程序Add Installer”
圖3. 添加服務(wù)安裝程序
2.4 在解決方案瀏覽器里雙擊服務(wù)安裝程序阴绢,然后在設(shè)計(jì)視圖中分別選中兩個(gè)安裝器分別配置好其屬性,包括服務(wù)的啟動(dòng)模式艰躺、描述呻袭、顯示名稱、運(yùn)行賬號(hào)等腺兴。服務(wù)安裝程序是用于用其它工具比如InstallUtil等進(jìn)行服務(wù)安裝的時(shí)候用的左电。
2.5 給項(xiàng)目添加新的入口點(diǎn)(entry point)。在項(xiàng)目里添加一個(gè)新的類页响,這里給類起名叫Program券腔,打開類的源代碼,用下面的代碼替換原有的類:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
string[] args = Environment.GetCommandLineArgs();
var findW = from arg in args
where arg.ToLower() == "w" || arg.ToLower() == "/w" || arg.ToLower() == "-w"
select arg;
if (args.Length == 2 && findW.Count() > 0)
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ServiceWatchdogSwitch()
};
ServiceBase.Run(ServicesToRun);
}
else
{
UIMode();
}
}
private static void UIMode()
{
// create a thread
Thread newWindowThread = new Thread(new ThreadStart(() =>
{
var mw = new MainWindow()
{
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen
};
mw.ShowDialog();
Thread.CurrentThread.Abort();
}));
// set the apartment state
newWindowThread.SetApartmentState(ApartmentState.STA);
// make the thread a background thread
newWindowThread.IsBackground = true;
// start the thread
newWindowThread.Start();
while (newWindowThread.ThreadState != ThreadState.Stopped) System.Threading.Thread.Sleep(50);
}
}
上面程序中拘泞,Main()里決定了,如果程序是帶w枕扫、/w或者-w參數(shù)啟動(dòng)的陪腌,那么讓它以服務(wù)的方式運(yùn)行,否則調(diào)用UIMode()進(jìn)入圖形界面非服務(wù)模式烟瞧。
2.6 在解決方案瀏覽器上點(diǎn)右鍵在彈出菜單中點(diǎn)“屬性Properties”诗鸭,在彈出的項(xiàng)目的屬性里,將入口點(diǎn)改成Program類如下圖:
至此参滴,改裝就完成了强岸,只需要將服務(wù)妥妥地安裝好就行了,注意啟動(dòng)命令要帶參數(shù)w砾赔、/w或者-w蝌箍。
達(dá)叔傻樂(darwin.zuo@163.com)