电脑爱好者,提供IT资讯信息及各类编程知识文章介绍,欢迎大家来本站学习电脑知识。 最近更新 | 联系我们 RSS订阅本站最新文章
电脑爱好者
站内搜索: 
当前位置:首页>> VB编程>>How-To Run Your Application as a Service:

How-To Run Your Application as a Service

来源:www.vbwire.com | 2006-11-13 | (有5036人读过)

How-To Run Your Application as a Service
by Chris J. Duke

Services        This article is the first in the "How-To" series exclusively by Advanced Visual Basic.

       So you've mastered Visual Basic, and now you want to release your latest masterpiece as a commercial application. At the last minute your boss tells you that your app has to run as a service under Windows NT. You tell him, "No problem!", and then you return to you workstation only to find out that your Visual Basic application can't do it. You search the Microsoft Knowledge Base for an answer, you search the net, the newsgroups, and then you wind up here... to the AVB How-To Series on Services. What you thought was impossible is now easier than you ever thought.

       This article will focus on the little known secret of how to run a Visual Basic 4.0 or 5.0 application as a service using Windows 95 and Windows NT 3.51 or higher. When your application is run as a service, your application can start prior to login so that your application is running at boot time. This is useful for network applications such as web servers, mail servers or any application that must be running all the time.

       Look for a follow-up article coming soon on how to instantly turn your Visual Basic application into a true NT service application simply by dropping a free ActiveX control onto a form.

Windows 95

       You may ask yourself, why would you need to run your VB application as a service using Windows 95. You may also ask if Windows 95, like Windows NT, can run applications as services.

       Yes, Windows 95 can run an application as a service. The reason why you would do this is to start your application prior to login. This is commonly done for servers such as web or mail servers. Due to Windows 95's lack of security, it is extremely easy to run your application as a service. This is not the case for Windows NT (see below).

       Running a VB application using Windows 95 is quite simple, all it really takes is a registry entry. While this is a hell of a lot easier to do in Win95 vs. WinNT, don't think that it's trouble-free. This section will also provide you with an important work-around for a Windows 95 quirk.

       To run your application as a service using Windows 95, add a new string value to this registry key:

       HKLM\SOFTWARE\Microsoft\
      Windows\CurrentVersion\RunServices

       For example, if your application was called "MicroSpud", just create a string value called "MicroSpud" and enter the full path to your executable into the data field. Follow these steps:

Add a new string value
Step 1: Add a new string value

Enter the path to your executable
Step 2: Enter the path to your executable

Fini!
Step 3: All done! Re boot and MicroSpud will start before login!

Windows 95 Tray Icon Quirk

       Now remember that "quirk" I mentioned earlier? Well here it is. If your application loads with an icon in the tray, you will want to read this work-around. When your application first loads, you most likely add your icon to the tray as one of your Form_Load or Main() events. If Windows 95 is set to auto logon upon re boot, this problem doesn't appear to exist. However, if a user is forced to login, what will happen is this:

  • Windows 95 starts
  • Your application starts as a service
  • Your application attempts to add its icon to the tray, but fails because there is no tray yet to add it to
  • The login dialog appears
  • The user enters in their username and password
  • The desktop loads
  • Your icon does not appear in the tray!

       The solution is to repeatedly call the Shell_NotifyIcon() API function until it returns a boolean true value. One way I've found to do this is to add a timer control, which is initially enabled, set at a 5 second interval. Put the Shell_NotifyIcon() call in its event (Timer1_Timer). Once the API call returns True, disable the timer. Voila!


Windows NT

       As you just found out, configuring your application run as a service under Windows 95 is a one-step process. NT, however, is a different animal entirely. Some might call it a beast. This method works well on Windows NT 3.51 or higher.

       One of the reasons why Windows NT is so much more difficult is because all services under NT are controlled by the Service Control Manager (SCM). While your application's whereabouts still resides in the registry, there's a few more keys which allow it run as a NT service.

       In order for any application to be able to be run as a NT service, it must first support multi-threading. This is because the application itself must create a few threads in order to communicate with the SCM. Since Visual Basic does not support threading, VB applications can not run as native NT service applications (VB5 supports "apartment model" threading, which is threading to a certain extent, but it is not real multi-threading.)

       Microsoft, realizing that this is a problem not only for Visual Basic applications, but most applications, developed a solution which works extremely well. They developed a small utility which is distributed with the Windows NT Resource Kit, and also available at the bottom of this page. The utility is called SRVANY.EXE and acts as a host (or service "wrapper") for your application. In other words, it becomes the service application which does all of the dirty work and communicates with the SCM for you. When it starts, it looks to the registry to find out where your application is located. If it finds it, it starts your application. The only drawback to using this utility is that when the SCM informs SRVANY to shut down, it uses the TerminateProcess() API to kill your VB application. This is a very crude way of shutting down an application.

       The configuration of your application as a NT service is straight forward, but not nearly as easy as Windows 95. Before I show you the step-by-step instructions, it is important to understand what is going on.

       There are two programs Microsoft developed which pulls this trick off. The first, as I just mentioned, is SRVANY.EXE. SRVANY is a program which resides in your WINNT\SYSTEM32 folder, or the folder where your application resides. While in the end you may want to think of your application as a NT service, it's really this little gem that is the true service. When your service starts, it actually starts SRVANY, which starts your application.

       The second program Microsoft developed is called INSTSRV.EXE. This program installs SRVANY as a NT service. It is a command-line driven program, and once used is no longer needed unless you wish to add another service which uses SRVANY, or you wish to un-install a previously added service. Keep it handy!

       While the documentation provided with SRVANY does a good job detailing the steps involved in its use, here's a visual step-by-step guide to installing SRVANY based on a fictional application called "MicroSpud":

Assumptions:
  • You are logged in as an Administrator. You cannot install a service otherwise
  • Your VB application, MicroSpud, resides here: c:\Program Files\MicroSpud\mspud.exe
  • You've installed both SRVANY.EXE and INSTSRV.EXE into MicroSpud's folder

Install app using INSTSRV


Step 1: Install SRVANY.EXE as a service using INSTSRV.EXE

Verify service was added


Step 2: Verify that your service got added by bringing up your services applet (control panel)

Configure service


Step 3: Configure your service's settings (defaults shown)

       At this point, your service has been created. However, if you were to try to start it now, it would fail. You next have to tell SRVANY where your VB application resides, so it can start it when the SCM starts SRVANY. Follow these steps to complete the installation of your new service:

Add a Parameters key


Step 1: Add a "Parameters" key:
  1. Start your registry editor
  2. Find your service under
    HKLM\SYSTEM\
    CurrentControlSet\Services\MicroSpud
  3. Create a "Parameters" key

Add an Application parameter


Step 2: Add an "Application" value:
  1. Open the "Parameters" key
  2. Create an "Application" string value (REG_SZ) within the "Parameters" key
  3. Edit "Application" and specify the full path of your app executable (including the extension)

Add optional values?


Step 3: Add optional values?
While not necessary, you may wish to add optional values to the "Parameters" key
  1. AppParameters (String) - Specify any parameters for your application
  2. AppDirectory (String) - Specify the current directory to use for your application

       Congratulations! You have just successfully turned your Visual Basic application into a Windows NT service. At this point, you are probably anxious to test it out. So, shutdown NT and restart it! Your application will start prior to login and be already running long before your desktop appears.

       There are some other bits of information you should know about SRVANY and your new NT service application: (Note that MicroSpud is used throughout the examples for consistency)

  • The registry values are not case sensitive
  • To un-install your service, use INSTSRV.EXE, eg: INSTSRV MicroSpud REMOVE
  • There are three ways to start your service:
    1. From the Services applet of the Control Panel
    2. Using the SC.EXE utility, eg: SC start MicroSpud
    3. Using the NET.EXE utility, eg: NET START MicroSpud
  • There are three ways to stop your service:
    1. From the Services applet of the Control Panel
    2. Using the SC.EXE utility, eg: SC stop MicroSpud
    3. Using the NET.EXE utility, eg: NET STOP MicroSpud
  • When the service is stopped, it terminates the application via the WIN32 TerminateProcess() API. This is a drastic way to end an application. For example, it would not allow the application to prompt the user to save changes. Therefore, it is recommended to close the application before stopping the service.
  • You may install SRVANY.EXE several times with different registry parameters (i.e. running different target applications) - just use a distinct service name for each instance (e.g. MicroSpud1, MicroSpud2 etc.)

       If your VB application interacts with the desktop, be sure to configure it to do so by clicking the Settings button for your service. You should also be aware of these programming considerations. Note that in order to trap the messages mentioned, you will need to use a utility such as SpyWorks from Desaware.

  • For WIN32 graphical applications: when the currently logged-in user is logging-off, all WIN32 top-level windows receive WM_QUERYENDSESSION and WM_ENDSESSION messages. Some WIN32 applications choose to terminate upon receipt of such messages. In order for your WIN32 application to survive logoff, it must not do that: instead, your windows procedure should call the default windows procedure on these messages.
  • For WIN32 Console (i.e. character-mode) applications: when the currently logged-in user is logging-off, all Console applications receive a CTRL_LOGOFF_EVENT event from the Console.
  • If your Console application has registered a Console event handler (via SetConsoleCtrlHandler), it must ignore CTRL_LOGOFF_EVENT in order to survive the logoff.

       Microsoft also advises you of the following:

  • If SRVANY fails to start your application, try specifying as current directory the directory where your application is installed (see "AppDirectory" registry key above). SRVANY may be running under an account different than the currently logged-on user therefore environment variables may be set differently: as a result, for example, the system might have been unable to find a DLL required for your application and running it from the application's directory might help.
  • Due to a restriction enforced by Windows NT on services, the application can either be interactive (have a Console, read keyboard input etc.) or have network access (not both at the same time).

Service Dependencies

       An undocumented feature for SRVANY (which applies to any service, actually) you should know about is the "DependOnService" value. Suppose your service depends on other services. How does your service know that other services are available when your service starts? For example, let's say your service is a web server. You will want to make sure that TCP/IP is available before your service starts.

       This binary value can be added to your service under the service key, along with the other values such as "DisplayName", "ObjectName", etc. Take a look at the following screen shot. It shows how I added a dependency for TCP/IP and the Event Log to my MicroSpud service. To find the name of the service to enter into the dialog box, use the key name from the registry for the service. For example, the key name under HKLM\SYSTEM\CurrentControlSet\Services for TCP/IP is "Tcpip", or for the event log you would enter "EventLog". For specifying more than one dependency, use 00 as a delimiter. This will show up as a period (.) in the ASCII display.

MicroSpud is dependent on TCP/IP and the Event Log

Windows 95 and Windows NT Services

       This article focused on configuring your Visual Basic 4.0 or 5.0 application to run as a service using Windows 95 and Windows NT 3.51 or higher. With the release of Visual Basic 5.0 came new capabilities never available for VB programmers, however you still cannot create native NT services. According to Desaware's advertisements, their new SpyWorks 5.0 product allows you to bypass SRVANY and create true Visual Basic NT services. I'll review this product (as well as a drop-in service OCX) and update this article in the future.

       I hope you found this information useful. It is provided for free to readers of the Advanced Visual Basic web site (http://vb.duke.net). Reproduction in whole or part is prohibited. Your comments and feedback are welcome, however I'm afraid that I cannot provide technical support for SRVANY and INSTSRV. Please contact Microsoft technical support or search their knowledge base for help.

Download SRVANY

       To download SRVANY.EXE, INSTSRV.EXE, and supporting documentation, click the following download link. It is the latest version at the time this article was written (Q2 1997) and supports Windows NT 3.51 and Windows NT 4.0.
SRVANY.ZIP (24k)

VB编程热门文章排行
网站赞助商
购买此位置

 

关于我们 | 网站地图 | 文档一览 | 友情链接| 联系我们

Copyright © 2003-2024 电脑爱好者 版权所有 备案号:鲁ICP备09059398号