Knowledge Base Nr: 00027 AutoInternetConnectService.cpp - http://www.swe-kaiser.de

Downloads:

MFC: implementation of an NT service using MFC (derived from www.codeguru.com)
if the service was started it waits some minutes before it starts a dos-batch-file
i use this service to connect the internet if the computer was started and nobody logs in within 5 minutes.

  
#include "stdafx.h"

#include <ras.h>

#include "ServiceApp.h"


CServiceApp theApp;


//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CServiceApp::CServiceApp()
: CNTService(TEXT("AutoInternetConnectService"), TEXT("Auto Internet Connect Service"))
, m_hStop(0)
{
}

CServiceApp::~CServiceApp()
{
}


BOOL CServiceApp :: InitInstance() {
RegisterService(__argc, __argv);
return FALSE;
}

void CServiceApp :: Run( DWORD argc, LPTSTR *argv)
{ // args not used in this small example
// report to the SCM that we're about to start
ReportStatus(SERVICE_START_PENDING);

m_hStop = ::CreateEvent(0, TRUE, FALSE, 0);

// You might do some more initialization here.
// Parameter processing for instance ...

// report SERVICE_RUNNING immediately before you enter the main-loop
// DON'T FORGET THIS!
ReportStatus(SERVICE_RUNNING);

// enter main-loop
// If the Stop() method sets the event, then we will break out of
// this loop.

//////////////////

const TIMEOUT = 2*60*60; //in seconds => 2 hours
const DELAYSTART = 3*60; //in seconds => 3 minutes

BOOL bStarted = FALSE;

int nDelay = 0;
while (::WaitForSingleObject(m_hStop, 10) != WAIT_OBJECT_0)
{
nDelay++;
::Sleep(1000);

if (nDelay < DELAYSTART)
continue;

if (nDelay == DELAYSTART)
{
//::MessageBox(NULL, TEXT("action! action! action!"), TEXT("MFC SampleService"), MB_OK|MB_SETFOREGROUND);

//WinExec("notepad.exe", SW_SHOW);
UINT nErr = WinExec("e:\\startauto\\my_start.bat", SW_SHOW);

CString strMsg;
strMsg.Format("action started! (return code: %d)", nErr);
bStarted = TRUE;
AddToMessageLog((LPSTR)(LPCSTR)strMsg, EVENTLOG_INFORMATION_TYPE);
}

if (nDelay >= TIMEOUT)
{
Stop();
AddToMessageLog(TEXT("Service time out!"));
//::MessageBox(NULL, TEXT("timeout! timeout! timeout!"), TEXT("MFC SampleService"), MB_OK|MB_SETFOREGROUND);
}
}

//stopped:
if (bStarted)
{
UINT nErr = WinExec("e:\\startauto\\my_stop.bat", SW_SHOW);

CString strMsg;
strMsg.Format("action stopped! (return code: %d)", nErr);
AddToMessageLog((LPSTR)(LPCSTR)strMsg, EVENTLOG_INFORMATION_TYPE);
//::MessageBox(NULL, TEXT("stop! stop! stop!"), TEXT("MFC SampleService"), MB_OK|MB_SETFOREGROUND);
}

//////////////////

if(m_hStop)
::CloseHandle(m_hStop);
}


void CServiceApp :: Stop() {
// report to the SCM that we're about to stop
// Note that the service might Sleep(), so we have to tell
// the SCM
// "The next operation may take me up to 3 seconds. Please be patient."
ReportStatus(SERVICE_STOP_PENDING, 2000);

if( m_hStop )
::SetEvent(m_hStop);
}