Pure VB truly implements stable NT Services

Source: Internet
Author: User

We are familiar with the NT Service. However, Microsoft does not support the use of VB to compile the NT service, even if a control is released for writing the NT Service, however, it is still clearly indicated on msdn that the stability of the NT Service written in VB is not guaranteed. This will inevitably disappoint the majority of VB fans. Although online search can get some sporadic instructions, there is no complete code that can run stably.
I remember I wrote a service with VB four or five years ago. Although it was not stable, it was able to run. I didn't expect some friends in the csdn forum to ask for such code these days. It seems that the NT Service is not easy for VB programmers. For this reason, I spent a whole day, improved the code and added instructions, making it easier and more stable to compile the NT Service in VB and providing rules to follow.
Well, let's take a look at the code and give a detailed description. If you need to reprint it, please indicate that it is from lyserver (after all, it is my hard work all day ). If you have any questions, please leave a message in your blog and I will try my best to answer them!

'*************************************** * *********************** <Br/> '* program name: modntsrv <br/> '* program function: Implementing the NT Service <br/>' * Author: lyserver <br/> '* contact information: http://blog.csdn.net/lyserver <br/> '********************************** * *************************** <br/> Option explicit <br/> 'service control constant <br/> Public Enum service_control <br/> service_control_stop = 1 & <br/> service_control_pause = 2 & <br/> service_control_c Ontinue = 3 & <br/> service_control_interrogate = 4 & <br/> service_control_shutdown = 5 & <br/> end Enum <br/> 'service status constant <br/> Public Enum service_state <br/> service_stopped = & H1 <br/> service_start_pending = & H2 <br/> service_stop_pending = & H3 <br/> service_running = & H4 <br/> service_continue_pending = & h5 <br/> service_pause_pending = & H6 <br/> service_paused = & H7 <br/> Delete = & h10000 <br/> end e Num <br/> 'Service Startup constant <br/> Public const service_system_start as long = & H1 <br/> Public const service_auto_start as long = & H2 <br/> Public const service_demand_start as long = & H3 <br/> 'service error control level <br/> private const service_error_normal as long = & H1 <br/> 'scm permission constant <br/> Public const standard_rights_required = & hf0000 <br/> Public const SC _manager_connect = & H1 <br/> Public const SC _manager_create_service = & H2 <br/> Public const unlock = & H4 <br/> Public const SC _manager_lock = & H8 <br/> Public const SC _manager_query_lock_status = & H10 <br/> Public const SC _manager_modify_boot_config & H20 <br/> Public const SC _manager_all_access = (standard_rights_required or SC _manager_connect or SC _manager_create_service or login or SC _manager_lock or SC _manager_query_loc K_status or SC _manager_modify_boot_config) <br/> 'Accept SCP Control Message constants <br/> Public const service_accept_stop as long = & H1 <br/> Public const service_accept_pause_continue as long = & H2 <br/> Public const service_accept_shutdown as long = & H4 <br/> 'Service permission constant <br/> Public const service_query_config = & H1 <br/> Public const service_change_config = & H2 <br/> Public const service_query_status = & H4 <br/> Public const se Rvice_enumerate_dependents = & H8 <br/> Public const service_start = & H10 <br/> Public const service_stop = & H20 <br/> Public const service_pause_continue = & h40 <br/> Public const service_interrogate = & h80 <br/> Public const service_user_defined_control = & h100 <br/> Public const service_all_access = (required or service_query_config or service_change_config or service_query_status or S Ervice_enumerate_dependents or service_start or service_stop or service_pause_continue or service_interrogate or service_user_defined_control) <br/> 'service type constant <br/> Public const service_win32_own_process as long = & H10 <br/> Public const service_win32_assist_process as long = & H20 <br/> Public const service_interactive_process long = & h100 <br/> Public const service_win32 as long = service_win32_own_pr Ocess + service_win32_assist_process <br/> 'auxiliary constant <br/> Public const Limit = 1066 & <br/> Public const error_service_exists = 1073 & <br/> Public const services_active_database = "servicesactive "<br/> Public const no_error = 0 'dderror </P> <p> Public type service_table_entry <br/> lpservicename as long <br/> lpserviceproc as long <br/> lpservicenamenull as long <br/> lpserviceprocnul L as long <br/> end type <br/> Public type service_status <br/> dwservicetype as long <br/> dwcurrentstate as long <br/> dwcontrolsaccepted as long <br/> dwwin32exitcode as long <br/> dwservicespecificexitcode as long <br/> dwcheckpoint as long <br/> dwwaithint as long <br/> end type <br/> 'nt Service API <br/> Public declare function openscmanager lib "advapi32.dll" alias "openscmanagerw" (byval lpmachinenam E As string, byval lpdatabasename as string, byval dwdesiredaccess as long) As long <br/> Public declare function closeservicehandle lib "advapi32.dll" (byval hscobject as long) as long <br/> Public declare function openservice lib "advapi32.dll" alias "openservicew" (byval hscmanager as long, byval lpservicename as string, byval dwdesiredaccess as long) as long <br/> Public declare function deletese Rvice lib "advapi32.dll" (byval hservice as long) As long <br/> Public declare function controlservice lib "advapi32.dll" (byval hservice as long, byval dwcontrol as long, lpservicestatus as service_status) as long <br/> Public declare function queryservicestatus lib "advapi32.dll" (byval hservice as long, lpservicestatus as service_status) As long <br/> Public declare function createservice lib "adv Api32.dll "alias" createservicew "(byval hscmanager as long, byval lpservicename as string, byval lpdisplayname as string, byval dwdesiredaccess as long, byval dwservicetype as long, byval dwstarttype as long, byval dwerrorcontrol as long, byval lpbinarypathname as string, byval lploadordergroup as string, lpdwtagid as long, byval lpdependencies as string, byval LP as string, byval lppassword as s Tring) As long <br/> Public declare function startservice lib "advapi32.dll" alias "startservicew" (byval hservice as long, byval dwnumserviceargs as long, byval lpserviceargvectors as long) as long <br/> Public declare function startservicectrldispatcher lib "advapi32.dll" alias "startservicectrldispatcherw" (lpservicestarttable as service_table_entry) As long <br/> Public declare Function Ervicectrlhandler lib "advapi32.dll" alias "handler" (byval lpservicename as long, byval lphandlerproc as long) As long <br/> Public declare function setservicestatus lib "handler" (byval hservicestatus as long, lpservicestatus as service_status) As long <br/> 'error handling API <br/> Public declare function getlasterror lib "Kernel32 "() as long <br/> 'thread API <br/> Public declare functio N createthread lib "Kernel32" (byval lpthreadattributes as long, byval dwstacksize as long, byval lpstartaddress as long, byval lpparameter as long, byval dwcreationflags as long, lpthreadid as long) as long <br/> Public declare function resumethread lib "Kernel32" (byval hthread as long) As long <br/> Public declare function terminatethread lib "Kernel32" (byval hthread as long, byval dwexitcode Long) As long <br/> Public declare function getcurrentthread lib "Kernel32" () as long <br/> Public declare function getcurrentthreadid lib "Kernel32 "() as long <br/> 'com API <br/> Public type guid <br/> data1 as long <br/> data2 as integer <br/> data3 as integer <br/> data4 (7) as byte <br/> end type <br/> Public iid_idispatch as guid <br/> Public declare function cow.alinterthreadinterfaceinstream Lib "ole32.dll" (riid as guid, byval punk as iunknown, ppstm as long) As long <br/> declare function cogetinterfaceandreleasestream lib "ole32.dll" (byval PSTM as long, riid as guid, punk as iunknown) As long <br/> Public declare function coinitialize lib "ole32.dll" (byval pvreserved as long) as long <br/> Public declare sub couninitialize lib "ole32.dll" () <br/> 'message processing API <br/> Public declare functi On getmessage lib "USER32" alias "getmessagea" (lpmsg as MSG, byval hwnd as long, byval wmsgfiltermin as long, byval wmsgfiltermax as long) as long <br/> Public declare function peekmessage lib "USER32" alias "peekmessagea" (lpmsg as MSG, byval hwnd as long, byval wmsgfiltermin as long, byval wmsgfiltermax as long, byval wremovemsg as long) As long <br/> Public const pm_remove as long = & H1 <br/> pub LIC declare function dispatchmessage lib "USER32" alias "dispatchmessagea" (lpmsg as MSG) As long <br/> Public declare function translatemessage lib "USER32" (lpmsg as MSG) as long <br/> Public const wm_quit as long = & H12 <br/> Public declare function postthreadmessage lib "USER32" alias "postthreadmessagea" (byval idthread as long, byval MSG as long, byval wparam as long, byval lparam as long) as l Ong <br/> Public type MSG <br/> hwnd as long <br/> message as long <br/> wparam as long <br/> lparam as long <br/> time as long <br/> Pt as currency <br/> end type <br/> private declare function waitforsingleobject lib "Kernel32" (byval hhandle as long, byval dwmilliseconds as long) As long <br/> Public declare sub sleep lib "Kernel32" (byval dwmilliseconds as long) <br/> 'bell API <br/> Public declare fun Ction messagebeep lib "USER32" (byval wtype as long) as long <br/> Public const mb_iconexclamation = & h30 & <br/> Public const mb_iconquestion = & H20 & <br/> Public declare function gettickcount lib "Kernel32 "() as long <br/> '==================================== ====================================< br/> 'module public variables <br/> '====== ========================================================== ============< br/> private const SERVICE_NAME as string = "m Yntservice "'service name <br/> private const display_name as string =" My NT Service "' service display name <br/> private m_szservicename as string <br/> private m_szdisplayname as string <br/> private m_status as service_status <br/> private m_hservicestatus as long <br/> private m_dwmainthreadid as long, m_dwservicethreadid <br/> private m_hservicethread as long <br/> '================== ================================== <Br/> 'function name: Main <br/> 'function description: main program entry point <br/> '============================== ======================================< br/> sub main () <br/> 'process command line parameters <br/> dim szargv as string <br/> szargv = ucase (TRIM (command) <br/> if left (szargv, 1) = "/" or left (szargv, "1") = "-" Then <br/> szargv = mid (szargv, 2) <br/> end if </P> <p> 'variable local system encoding <br/> m_szservicename = strconv (SERVICE_NAME, vbunicode) <br/> m_szdisplayname = s Trconv (SERVICE_NAME, vbunicode) </P> <p> 'If a parameter exists, process it. <br/> If Len (szargv)> 0 then <br/> If szargv = "I" or szargv = "Install" or szargv = "regserver" then <br/> 'installation service <br/> If install () then <br/> msgbox vbcrlf & "has been installed successfully! "& Vbcrlf, vbinformation," prompt "<br/> else <br/> msgbox vbcrlf &" Service Installation failed! "& Vbcrlf, vbexclamation, "prompt" <br/> end if <br/> exit sub <br/> elseif szargv = "U" or szargv = "Uninstall" or szargv = "unregserver" then <br /> 'uninstall the service <br/> If uninstall () then <br/> the msgbox vbcrlf & "service has been uninstalled successfully! "& Vbcrlf, vbinformation," prompt "<br/> else <br/> msgbox vbcrlf &" An error occurred while uninstalling the service! "& Vbcrlf, vbexclamation," prompt "<br/> end if <br/> exit sub <br/> else <br/> msgbox vbcrlf &" unsupported parameter, stop running! ", Vbcritical," warning "<br/> exit sub <br/> end if </P> <p> 'No parameter, determine whether the service has been installed, otherwise, exit <br/> if not isinstalled then exit sub </P> <p> 'to obtain the master thread ID for backup <br/> m_dwmainthreadid = getcurrentthreadid () </P> <p> 'try to start the service <br/> dim result as long <br/> dim ste as service_table_entry </P> <p> Ste. lpservicename = strptr (m_szservicename) <br/> Ste. lpserviceproc = getfuncaddr (addressof servicemain) <br/> result = startservicectrldispatcher (STE) </P> <p> 'if the service is successfully started, then enter the message loop to be <br/> If result <> 0 then <br/> dim umsg as MSG <br/> do while getmessage (umsg, 0, 0, 0) <br/> loop <br/> end if </P> <p> 'wait for the end of the service thread <br/> waitforsingleobject m_hservicethread, 800 <br/> end sub <br/> '======================== ===========================< br/> 'function name: isinstalled <br/> 'function description: determine whether the service has been installed <br/> '================================== ========================================< br/> Public Function isinstalled () as Boolean <br/> dim bsuccess as long <br/> dim hscm as long, hservice as long <br/> hscm = openscmanager (vbnullstring, vbnullstring, SC _manager_all_access) <br/> If hscm <> 0 then <br/> hservice = openservice (hscm, m_szservicename, service_query_config) <br/> If hservice <> 0 then <br/> bsuccess = true <br/> call closeservicehandle (hservice) <br/> end if <br/> call closeservicehandle (hscm) <br/> end if <br/> isinstalled = bsuccess <br/> end function <br/> '============ =====================================================< br/> 'function Name: install <br/> 'function description: install the service <br/> '==================================== ====================================< br/> Public Function install () as Boolean <br/> dim bsuccess as Boolean <br/> dim hscm as long, hservice as long <br/> dim szfilepath as string 'unicode encoding <br/> If isinstalled () then <br/> bsuccess = true <br/> else <br/> hscm = openscmanager (vbnullstring, vbnullstring, SC _manager_all_access) <br/> If hscm <> 0 then <br/> szfilepath = strconv (App. path & "/" & App. exename &". EXE ", vbunicode) <br/> hservice = createservice (hscm, m_szservicename, m_szdisplayname, _ <br/> service_all_access, region, _ <br/> service_deman_start, service_error_normal, _ <br/> szfilepath, vbnullstring, byval 0 &, vbnullstring) <br/> If hservice <> 0 then <br/> bsuccess = true <br/> call closeservicehandle (hservice) <br/> end if <br/> call closeservicehandle (hservice) <br/> end if <br/> install = bsuccess <br/> end function <br/> '======== ========================================================== =====< br/> 'function name: uninstall <br/> 'function description: detach a service <br/> '========================================== ====================================< br/> Public Function uninstall () as Boolean <br/> dim bsuccess as Boolean <br/> dim hscm as long, hservice as long </P> <p> if not isinstalled then <br/> bsuccess = true <br/> else <br/> hscm = openscmanager (vbnullstring, vbnullstring, SC _manager_all_access) <br/> If hscm <> 0 then <br/> hservice = openservice (hscm, m_szservicename, service_stop or delete) <br/> If hservice <> 0 then <br/> dim status as service_status <br/> call controlservice (hservice, service_control_stop, status) <br/> bsuccess = deleteservice (hservice) <br/> call closeservicehandle (hservice) <br/> end if <br/> call closeservicehandle (hscm) <br/> end if <br/> uninstall = bsuccess <br/> end function <br/> '======== ========================================================== =====< br/> 'function name: servicemain <br/> 'function description: service Entry thread <br/> '================================ ====================================< br/> Public sub servicemain (byval dwargc as long, byval lpszargv as long) <br/> dim HR as long <br/> dim umsg as MSG <br/> dim lstarttime as long </P> <p> 'get the service thread handle <br/> m_hservicethread = getcurrentthread () </P> <p> 'get the service thread id <br/> m_dwservicethreadid = getcurrentthreadid () <br/> 'register SCP callback function address with SCM <br/> m_hservicestatus = registerservicectrlhandler (strptr (m_szservicename), addressof handler) </P> <p> 'the notification SCM service is starting <br/> sendstatustoscm service_start_pending <br/> 'initialize COM, let the thread enter the apartment thread mode <br/> hR = coinitialize (byval 0 &) </P> <p> 'indicates that the SCM service is running <br/> sendstatustoscm service_running </P> <p>'. Enter the service message loop. <br/> lstarttime = gettickcount () <br/> do while true <br/> call peekmessage (umsg, 0, 0, 0, pm_remove) <br/> If umsg. message = wm_quit then exit do <br/> dispatchmessage umsg <br/> If gettickcount () -lstarttime> 1000 then <br/> lstarttime = gettickcount <br/> messagebeep-1 <br/> end if <br/> sleep 1 <br/> loop </P> <p> 'cancel apartment thread mode <br/> call couninitialize <br/> 'indicates that the SCM service has stopped. <br/> sendstatustoscm service_stopped </P> <p>' indicates that the master is notified. message loop after the thread ends <br/> postthreadmessage m_dwmainthreadid, wm_quit, 0, 0 <br/> end sub <br/> '======================== ===========================< br/> 'function name: handler <br/> 'function description: receive and process SCP Control Messages <br/> '======================== ======================================< br/> Public sub handler (byval dwopcode as long) <br/> select case dwopcode <br/> case service_control_stop ': When an SCP-issued stop control is received, <br/>' notify SCM that the service is about to stop <br/> sendstatustoscm service_stop_pending <br/> 'notify the service thread to end the message loop <br/> call postthreadmessage (m_dwservicethreadid, wm_quit, 0, 0) <br/> case service_control_pause <br/> case service_control_continue <br/> case service_control_interrogate <br/> case service_control_shutdown 'when the SCP shutdown control is received <br/> 'notification the SCM service is about to stop <br/> sendstatustoscm service_stop_pending <br/> 'notifies the service thread to end the message loop <br/> call postthreadmessage (m_dwservicethreadid, wm_quit, 0, 0) <br/> case else <br/> end select <br/> end sub <br/> '================ =======================================================< br /> 'function Name: sendstatustoscm <br/> 'function description: auxiliary Function of service status setting <br/> '====================================== ======================================< br/> Public Function sendstatustoscm (optional byval dwcurrentstate as service_state = 0) as long <br/> dim status as service_status </P> <p> status. dwservicetype = service_win32_own_process <br/> If dwcurrentstate <> 0 then <br/> status. dwcurrentstate = dwcurrentstate <br/> end if <br/> If dwcurrentstate = service_start_pending then <br/> status. dwcontrolsaccepted = 0 <br/> else <br/> status. dwcontrolsaccepted = service_accept_stop or _ <br/> service_accept_shutdown 'determines which control messages of SCP are received. <br/> end if <br/> sendstatustoscm = setservicestatus (m_hservicestatus, status) <br/> end function <br/> '========================== =======================================< br/> 'function name: getfuncaddr <br/> 'function description: obtain the Helper function of the function pointer <br/> '================================ ======================================< br/> Public Function getfuncaddr (byval lfuncaddr as long) as long <br/> getfuncaddr = lfuncaddr <br/> end function </P> <p> 
 
Note: the code has been uploaded to the csdn resource center.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.