Question

NTSvc.ocx won't process shutdown event

Asked by: bartsmit

I guess most experts here will be familiar with the ntsvc.ocx and its many sample programs. I have created a service with this which runs great. The *only* problem is that the service needs to tidy up some stuff on shutdown.

For the life of me, I cannot get the shutdown event to be handled. I have attached a sample app which runs off a form with the ntsvc.ocx, a timer and a status bar control. The only modifications that I've made to the sample code are a series of beep statements. The service happily beeps once for start and twice for stop. However it does not make a sound when the machine reboots.  I'd be really happy if somebody can hack it so it gives three beeps just before Windows shuts down.

I have tried adding a NTService1_Shutdown() handler,  Form_UnloadQuery() and Form_Unload() subs but I cannot get the service to run code on shutdown.

This is bugging me and I really like to fix this badly, hence the high point value. Any sample code that runs something on a reboot is fine, as I need to port it back to my main project anyway. My real code doesn't have .interactive=true and only outputs to the app log.

Thanks

===================== sample code ===============
Option Explicit
Private Sub Form_Load()
On Error GoTo Err_Load
    Dim strDisplayName As String
    Dim bStarted As Boolean
    strDisplayName = NTService1.DisplayName
    StatusBar.Panels(1).Text = "Loading"
    If Command = "-install" Then
        ' enable interaction with desktop
        NTService1.Interactive = True
        If NTService1.Install Then
            Call NTService1.SaveSetting("Parameters", "TimerInterval", "1000")
            MsgBox strDisplayName & " installed successfully"
        Else
            MsgBox strDisplayName & " failed to install"
        End If
        End
    ElseIf Command = "-uninstall" Then
        If NTService1.Uninstall Then
            MsgBox strDisplayName & " uninstalled successfully"
        Else
            MsgBox strDisplayName & " failed to uninstall"
        End If
        End
    ElseIf Command = "-debug" Then
        NTService1.Debug = True
    ElseIf Command <> "" Then
        MsgBox "Invalid command option"
        End
    End If
    Timer.Interval = CInt(NTService1.GetSetting("Parameters", "TimerInterval", "2000"))
    ' enable Pause/Continue. Must be set before StartService
    ' is called or in design mode
    NTService1.ControlsAccepted = svcCtrlPauseContinue + svcCtrlShutdown
    ' connect service to Windows NT services controller
    NTService1.StartService
Err_Load:
    Call NTService1.LogEvent(svcMessageError, svcEventError, "[" & Err.Number & "] " & Err.Description)
End Sub

Private Sub NTService1_Continue(Success As Boolean)
On Error GoTo Err_Continue
    Timer.Enabled = True
    StatusBar.Panels(1).Text = "Running"
    Success = True
    Call NTService1.LogEvent(svcEventInformation, svcMessageInfo, "Service continued")
Err_Continue:
    Call NTService1.LogEvent(svcMessageError, svcEventError, "[" & Err.Number & "] " & Err.Description)
End Sub

Private Sub NTService1_Control(ByVal lngEvent As Long)
On Error GoTo Err_Control
    Beep
    Beep
    Beep
Err_Control:
    Call NTService1.LogEvent(svcMessageError, svcEventError, "[" & Err.Number & "] " & Err.Description)
End Sub


Private Sub NTService1_Pause(Success As Boolean)
On Error GoTo Err_Pause
    Timer.Enabled = False
    StatusBar.Panels(1).Text = "Paused"
    Call NTService1.LogEvent(svcEventError, svcMessageError, "Service paused")
    Success = True
Err_Pause:
    Call NTService1.LogEvent(svcMessageError, svcEventError, "[" & Err.Number & "] " & Err.Description)
End Sub


Private Sub NTService1_Start(Success As Boolean)
On Error GoTo Err_Start
    Beep
    StatusBar.Panels(1).Text = "Running"
    Success = True
Err_Start:
    Call NTService1.LogEvent(svcMessageError, svcEventError, "[" & Err.Number & "] " & Err.Description)
End Sub


Private Sub NTService1_Stop()
On Error GoTo Err_Stop
    Beep
    Beep
    StatusBar.Panels(1).Text = "Stopped"
    Unload Me
Err_Stop:
    Call NTService1.LogEvent(svcMessageError, svcEventError, "[" & Err.Number & "] " & Err.Description)
End Sub


Private Sub Timer_Timer()
On Error GoTo Err_Timer
    StatusBar.Panels(2).Text = Format(Now(), "hh:mm:ss")
Err_Timer:
    Call NTService1.LogEvent(svcMessageError, svcEventError, "[" & Err.Number & "] " & Err.Description)
End Sub

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-07-17 at 11:51:44ID20681874
Topic

Visual Basic Programming

Participating Experts
4
Points
500
Comments
22

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. How to detect a beep event in vba
    From within Microsoft Access 2002, I am sending keystrokes via the SendKeys command to another application. If the keystroke sequence is invalid for the other application, it will generate a beep. I need to be able to detect when a beep has been generated. How can I detect...
  2. Paviliona324x Wierd Beeping on Shutdown
    Hey Guys, A friend of mine has a Paviliona324x (XP Pro SP2), and he is reporting strange problems on shutdown... When he leaves the system on for a while (4 hours or more), whenever he tries to shut the system down, a continuous beep sounds(from the internal speaker), and th...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: BiffoPosted on 2003-07-17 at 12:23:05ID: 8945733

What about creating a task to run at a certain time independent of your app?

 

by: bartsmitPosted on 2003-07-17 at 15:46:29ID: 8947463

the service IS the app. Basically it opens network connections to a server. Whenever the machine reboots, some connections are left open and these cause problems when the service starts again after the reboot.

Restarting the service is fine, since I can tidy up the open connections but shutdown is not. I don't get a chance to tidy up and the connection fails on restart.

I don't need to run timed tasks, this is built into the service.

Also, it is very difficult to predict the time of the next shutdown ;-)

 

by: TeodorPosted on 2003-07-17 at 16:41:37ID: 8947900

Hi,
You should look in the MSDN for following function: RegisterServiceCtrlHandlerEx


Private Declare Function RegisterServiceCtrlHandlerEx Lib "ADVAPI32.dll" ( _
       ByVal lpServiceName As String, _
       ByRef lpHandlerProc As LPHANDLER_FUNCTION_EX, _
       lpContext As Any) As Long

You can use it anywhere in your poject.
BUT, the CallBack function should be used Public and in a module:
One of the events that CallBack function will receive is:
"SERVICE_CONTROL_SHUTDOWN - Notifies a service that the system is shutting down so the service can perform cleanup tasks."

I don't have time right now to test if is working in VB or not.

I hope this will help you a litle bit.
Teodor




 

by: TeodorPosted on 2003-07-17 at 16:47:57ID: 8947931

Hi,
You should look in the MSDN for following function: RegisterServiceCtrlHandlerEx


Private Declare Function RegisterServiceCtrlHandlerEx Lib "ADVAPI32.dll" ( _
       ByVal lpServiceName As String, _
       ByRef lpHandlerProc As LPHANDLER_FUNCTION_EX, _
       lpContext As Any) As Long

You can use it anywhere in your poject.
BUT, the CallBack function should be used Public and in a module:
One of the events that CallBack function will receive is:
"SERVICE_CONTROL_SHUTDOWN - Notifies a service that the system is shutting down so the service can perform cleanup tasks."

I don't have time right now to test if is working in VB or not.

I hope this will help you a litle bit.
Teodor


 

by: bartsmitPosted on 2003-07-18 at 02:43:07ID: 8950324

Thanks Teodor but I believe that this is the function that is encapsulated in the OCX as the .ControlsAccepted property and the NTService1_Control event. I'm not convinced that the program will be able to register with the service handler to get this event.

 

by: bartsmitPosted on 2003-07-18 at 03:09:47ID: 8950485

BTW for those who want to take the code for a spin, the sample I used is available for download here: http://www.vbwire.com/advanced/howto/ntsrvocx.exe You can also download the compiled OCX from them: http://www.vbwire.com/advanced/howto/ntsrvocx.zip

 

by: TeodorPosted on 2003-07-18 at 06:13:23ID: 8951439

Hi Bart,
Ntsvc.ocx has some bugs. Have a look and at these links:

NT Service (Updated!) : http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=6478&lngWId=1
NTService 1.1 : http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=15039&lngWId=1

I have to develop a similar project like yours: an exe that should act as a server for a few clients and it should run as a service.

Teodor


 

by: BiffoPosted on 2003-07-18 at 08:33:11ID: 8952707

This NTSvc fires a shutdown event doesn't it? Isn't NTSsvc an old MS ole VB sample program?


 

by: bartsmitPosted on 2003-07-18 at 10:13:33ID: 8953599

Biffo, feel free to compile the sample for the ocx and see for yourself ;-)
It is supposed to handle the shutdown event but I can't seem to execute any code.

 

by: BiffoPosted on 2003-07-18 at 10:33:55ID: 8953747

Well hell, if I am gonna recompile NTSvc I could easily fix the problem since to my understanding the problem is that it is missing this in CNtSvcCtrl::OnHandler:

case SERVICE_CONTROL_SHUTDOWN: // 5
  pService->FireControl(svcCtrlShutdown);
  SetStatus (SERVICE_STOPPED);
  break;


Add that, compile and problem *should* be solved.

 

by: bartsmitPosted on 2003-07-18 at 14:46:12ID: 8955561

Thanks Biffo,

Very interesting suggestion. I inserted the code in the CNtSvcCtrl::OnHandler in NtsvcCtl.cpp but I got an "error C2065: 'svcCtrlShutdown' : undeclared identifier" when compiling.

My C++ is fairly poor so I'm not sure how to fix this. I really don't care to run any different code on shutdown as I would on service stop, so I have pasted the code from //1 into the //5 case like so:

case SERVICE_CONTROL_SHUTDOWN: // 5
  m_pThis->StopService();
  break;

In the hope that this will execute the NTService1_Stop handler in my VB code on shutdown. I will test with both that and the 1.1 release over the weekend.

Do you think that it is easy to fix the //5 case to fire a separate event as per the documentation? It would be nice for other people who use this code in future to have a properly functioning svcCtrlShutdown handler but I'm more interested in a working service for now.

 

by: bartsmitPosted on 2003-07-21 at 03:09:20ID: 8966150

I'm not having much luck using the recompiled version of ntsvc.ocx.

I've added the code to the shutdown case statement as above, and it compiles with 0 errors and 3 warnings:
MIDL2039 : interface does not conform to [oleautomation] attribute : [ Parameter 'Success' of Procedure 'Continue' ( Dispinterface '_DNtsvcEvents' ) ]
The same warning is displayed for procedures 'Pause' and 'Start'

When I try and incorporate the updated ocx in my setup script, it comes back with "Component 'NTSVC.ocx' or one of its dependencies not correctly registered: a file is missing or invalid"

Yet, in the dependency walker both files are showing the same dll's (mfc42, msvcrt, kernel32, user32, gdi32, advapi32 and oleauth32) and the new ocx will register correctly from regsvr32.

Is this related to the 1.1 project being set to German? Is it possible to modify the original MS distributed code? According to most related websites, the code was meant to be compiled in VC++ 4.0 and I'm on 6.0 SP5.

Any pointers on how to recompile and use the ocx?

 

by: bartsmitPosted on 2003-07-21 at 03:18:53ID: 8966185

The error "Component 'NTSVC.ocx' or one of its dependencies not correctly registered: a file is missing or invalid" also comes up when I run ntservice1 -install by hand, so it is independent of the install script.

 

by: BiffoPosted on 2003-07-21 at 17:54:11ID: 8972300

mmm hmmm all expected.  Ok, you are using the quirky MSVS to comply with: do you get a working .ocx if compiled without any mods to the source? The undeclared identifier is no big deal with MSVS, I used to get those right from left, like when I was using _FUNCTION_ which VS didn't recognize <g> Will have to declare svcCtrlShutdown. When I get time I'll d/l the source and go over it instead of blindly commenting.




 

by: TeodorPosted on 2003-07-22 at 02:07:21ID: 8974695

Try to compile the project that you'll found at this link:
NTService 1.1 : http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=15039&lngWId=1

 

by: bartsmitPosted on 2003-07-22 at 04:22:26ID: 8975411

Biffo, the 1.1 source that Teodor pointed me to compiles with or without the mod for shutdown, but neither OCX will work. I haven't been able to compile the original MS source, since I don't know how to open the project in VC++ 6.0 without a .dsw or .dsp project file.

Teodor, I tried to compile the second link you sent me, but it fails on the dependencies.

I'm sure that I'll have this fixed in no time if only I can compile a good OCX from source.

 

by: TeodorPosted on 2003-07-22 at 18:31:19ID: 8981844

OK, then try this one:
http://www.teodorsportfolio.go.ro/for_bart.zip
You'll find have .dsw and .dsp files of the project and let us know if it woked or not.


 

by: TeodorPosted on 2003-07-22 at 18:39:46ID: 8981892

If you have any problem with that link you can dld the zip from this page:
http://www.teodorsportfolio.go.ro/for_bart.html

Teodor

 

by: bartsmitPosted on 2003-07-24 at 02:16:42ID: 8993504

Thanks Guys,

Your help has been outstanding.

After some minor error messages, the OCX compiled fine from Teodor's project with Biffo's source edit. It now processes the stop event on shutdown flawlessly.

Biffo, I've posted a question with your points here: http://www.experts-exchange.com/Programming/Programming_Languages/Visual_Basic/Q_20688829.html

It was a pleasure working with you both.

Bart...

 

by: TeodorPosted on 2003-07-24 at 03:34:20ID: 8993831

Hi Bart,
Thank you for your appreciation.
Teodor

 

by: PaulALongPosted on 2003-09-08 at 23:16:24ID: 9316386

Hi Bart,

I am having the same problem as you were here with the NTSVC.OCX, it won't process my shutdown events either.  I don't have any way to re-compile this OCX as described here, is there any way you or someone else could please e-mail (paullong@cox.net) me the fixed version? or post it somewhere so that i can down load it.

Thank You!

Paul

 

by: ShragelPosted on 2009-08-22 at 21:58:21ID: 25161399

Can anyone post a new compiled ntsvc.ocx with the above correction?

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...