Creating Your Own Windows Service


This article was contributed by Karl Moore.

Environment: Visual Basic, Internet, Web Services

A Windows service is one of those often-invisible programs that typically starts with the operating system and hangs about, silently running, until you shut down. Such services include virus checkers, disk-monitoring applications, and security programs.

If you wanted to create one of these programs just a couple of years ago, you'd either have to buy an expensive third-party VB add-on to assist in the process—or learn C++. In Visual Studio .NET, you can just do it directly in your fave programming language, in about five minutes flat.

How? Well, start off by creating your own Windows Service project in Visual Studio .NET. You'll be shown a relatively blank design screen. What you do next is really up to you.

Figure 1: Creating a Windows Service project

One of the most common procedures in designing your Windows service is to add a Timer component and have it fire your service code every x seconds or minutes. How can you get this to work? While still in Design mode, open the Components tab of the toolbox and drag and drop a Timer component onto your service. Change its Interval property to the number of milliseconds between times you want your code to run. (Remember, 1,000 milliseconds equals one second. If you want your code to run every ten minutes, for example, set this to 60000.) Next, add code to respond to the Elapsed event of your timer; this code may check for the availability of a Web site, process any outstanding database requests, remove redundant files, perform some form of calculation—anything, really.

Another component that you may wish to use in your service is the FileSystemWatcher. This enables you to monitor a particular file or directory for changes. When these occur, events are raised. You can use this to dynamically monitor an area on your machine for alterations. As an example, you may be creating a system that keeps backups alongside an audit log, or records important system file changes in the event log.

A further possibility is to create a service as the server part of a remoting solution. Your service simply sits in the background, waiting for clients to connect in and "talk."

You also can add code to respond to the overridden OnStart and OnEnd events. These are added by default to your service—just add code as necessary. For example, you may run a Timer1.Start during the OnStart event and a Timer1.Stop at the OnEnd event.

Your service also has the capability to override other events, such as OnPause, OnContinue, OnShutdown, and so on. You can respond to these by, in the Code window, selecting (Overrides) from the first dropdown box, and the event in the second. A skeletal overrides event will be created for you. Again, add code as you deem fit.

So, you finally decided how to design your own service and have just finished coding. Next, set its properties. To do this, open your service in Design mode and click on a blank region of the screen. In the Properties window, alter the Can... settings (such as CanPauseAndContinue and CanShutdown), typically depending on the events you have coded. You may also want to change the ServiceName.

Installing Your Service

Well, that's your service finished, but, to install it we need to perform one last step. Right-click on your service in Design mode, and select Add Installer. This adds a new component to your project, containing a couple of objects that are used to provide details of your service during the installation. If you don't add this installer component, the installation simply doesn't work.

Top Tip If you want to add special code to run during installation, you can do this by responding to some of the events behind this installer. Find out more by looking up "Windows Service applications, adding installers to" in the Help index.

Peruse the properties of the two objects added: typically ServiceProcessInstaller1 and ServerInstaller1. The most important properties here are the DisplayName, which is the friendly name given to a service; StartType, which determines whether the service starts Manual or Automatic; and Account, which determines the account your service logs on under. Edit if required.



Click here for a larger image.

Figure 2: Setting up our installer component

And then? That's it! Just click on Build > Build Solution to compile your application.

How do you actually get your service up and running? Well, include your project in a regular VS .NET setup and it'll do the job of installing it for you. Alternatively, you can go manual and use the InstallUtil.exe application to get it installed. Launch the Visual Studio .NET Command Prompt and type the following line:

InstallUtil.exe c:\YourProject\bin\YourApp.exe

Make sure you pay attention to the messages from this utility. If all is well, you've just completed your installation. Use the Server Explorer in Visual Studio .NET to check out the services running on your local machine (or others on your network). After installing, yours should now be in the list; right-click and select Start to set it off. You can alter whether it starts by default by using the Services application (Program Files > Administrative Tools > Services), or setting the StartType property previously mentioned.

Figure 3: Viewing Services via the Server Explorer

But what good would be an install without an uninstall? Here's how to remove your Windows service using the InstallUtil.exe prompt once more:

InstallUtil.exe /u c:\YourProject\bin\YourApp.exe

And that's really all there is to know about creating your very own Windows service. Easy!

About the Author

Karl Moore (MCSD, MVP) is an experience author living in Yorkshire, England. He is the author of numerous technology books, including the new Ultimate VB.NET and ASP.NET Code Book (ISBN 1-59059-106-2, $49.99), plus regularly features at industry conferences and on BBC radio. Moore also runs his own creative consultancy, White Cliff Computing Ltd. Visit his official Web site at www.karlmoore.com.



About the Author

Karl Moore

Karl Moore (MCSD, MVP) is an experience author living in Yorkshire, England. He is the author of numerous technology books, including the new Ultimate VB .NET and ASP.NET Code Book (ISBN 1-59059-106-2), plus regularly features at industry conferences and on BBC radio. Moore also runs his own creative consultancy, White Cliff Computing Ltd. Visit his official Web site at www.karlmoore.com.

Comments

  • Клиника Илая - инновационный медицинский центр

    Posted by HeepsyMed on 04/21/2013 05:23pm

    http://www.kava-time.com.ua/kiev/klinika-ilaya-innovatsionniy-meditsinskiy-tsentr.html Новейшие методики лечения ilaya - упрощение и удешевление сложных операций Ультрасовременный эндоскоп PENTAX (Япония) экспертного класса имеет уникальную мочь ранней диагностики новообразований желудочно-кишечного тракта с через программы «i-scan» (виртуальная хромоэндоскопии) без введения контрастного вещества (1-й орудие в СНГ). Уписывать возможность одновременного с диагностикой выполнения эндоскопических операций. Диагностика и лечение почечно-каменной болезни биполярным резектоскопом Richard Wolf (Германия) и лазерной установкой Lumenis (США) позволяет фрагментировать утес с всякий локализации (почка, мочеточник, мочевой пузырь и мочеиспускательный канал) и восстановить уродинамику изза один визит. В ilaya возможно действие эндоскопических операций по лечению доброкачественной гиперплазии предстательной железы (аденома), включая ТУРП (Трансуретральная резекция простаты) и лазерную энуклеацию простаты с помощью Lumenis (США). Мы перевели тяжелые хирургические операции в величина «Хирургии одного дня».

    Reply
  • windows Sheduler

    Posted by dhamalnilesh on 08/17/2006 12:42am

    I want to make shedular. like windows this shedular must run as per settings made in module. please if any know that send me. (in visual basic 6.0) Thanks, Nilesh

    Reply
  • Windows event

    Posted by hong ly on 06/11/2006 10:03am

    how can I know when the user select a file or folder?

    Reply
  • Network

    Posted by hong ly on 06/11/2006 09:59am

    How can I know the computer in my LAN is turn on or off? Please write it in VB6.o

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • VMware vCloud® Government Service provided by Carpathia® is an enterprise-class hybrid cloud service that delivers the tried and tested VMware capabilities widely used by government organizations today, with the added security and compliance assurance of FedRAMP authorization. The hybrid cloud is becoming more and more prevalent – in fact, nearly three-fourths of large enterprises expect to have hybrid deployments by 2015, according to a recent Gartner analyst report. Learn about the benefits of …

Most Popular Programming Stories

More for Developers

RSS Feeds