Refer to the. NET windows programming series (14) on msdn: Windows Service (level 200).
http://www.microsoft.com/china/msdn/events/webcasts/shared/webcast/Series/NETWindows.aspx
Public partial class server1: servicebase {thread threadform = NULL; Public server1 () {initializecomponent ();} [dllimport ("user32.dll")] Static extern int get1_topwindow (); [dllimport ("user32.dll")] Static extern intptr getprocesswindowstation (); [dllimport ("kernel32.dll")] Static extern intptr getcurrentthreadid (); [dllimport ("user32.dll")] static extern intptr getthreaddesktop (intptr dwthre AD); [dllimport ("user32.dll")] Static extern intptr openwindowstation (string a, bool B, int C); [dllimport ("user32.dll")] static extern intptr opendesktop (string lpszdesktop, uint dwflags, bool finherit, uint dwdesiredaccess); [dllimport ("user32.dll")] Static extern intptr closedesktop (intptr P ); [dllimport ("rpcrt4.dll", setlasterror = true)] Static extern intptr rpcimpersonateclient (int I); [dlli Mport ("rpcrt4.dll", setlasterror = true)] Static extern intptr rpcreverttoself (); [dllimport ("user32.dll")] Static extern intptr setthreaddesktop (intptr ); [dllimport ("user32.dll")] Static extern intptr setprocesswindowstation (intptr A); [dllimport ("user32.dll")] Static extern intptr closewindowstation (intptr ); protected override void onstart (string [] ARGs) {threadform = new thread (new threads Tart (formshow); threadform. Start ();} protected override void onstop () {If (threadform! = NULL) {If (threadform. isalive) {threadform. abort (); threadform = NULL ;}} void formshow () {getmediatopwindow (); intptr hwinstasave = getprocesswindowstation (); intptr dwthreadid = getcurrentthreadid (); intptr hsf-save = getthreaddesktop (dwthreadid); intptr hwinstauser = openwindowstation ("winsta0", false, 33554432); If (hwinstauser = intptr. zero) {rpcreverttoself (); return;} setprocesswindowstation (hwinstauser); intptr hsf-user = opendesktop ("default", 0, false, 33554432); rpcreverttoself (); if (hsf-user = intptr. zero) {setprocesswindowstation (hwinstasave); closewindowstation (hwinstauser); return;} setthreaddesktop (hsf-user); intptr dwguithreadid = dwthreadid; form1 F = new form1 (); // This form1 can contain policyicon, which can be displayed in the tray. You can click the tray icon to set the system. windows. forms. application. run (f); dwguithreadid = intptr. zero; setthreaddesktop (hsf-save); setprocesswindowstation (hwinstasave); closedesktop (hsf-user); closewindowstation (hwinstauser );}}