Winlogon notify的Vista移植
By MikeFeng QQ: 76848502
//
#pragma comment (lib,"Secur32")
#define _WIN32_WINNT 0x6000
#include <windows.h>
#include <iostream>
#include <winuser.h>
using namespace std;
#define SERVICE_NAME "Vista Service For Logoff Event"
HANDLE terminateEvent = NULL;
SERVICE_STATUS_HANDLE serviceStatusHandle;
SERVICE_STATUS MyServiceStatus;
HANDLE threadHandle = NULL;
BOOL pauseService = FALSE;
BOOL runningService = FALSE;
BOOL InitService();
VOID terminate(DWORD error);
VOID ICSEventLogoff();
VOID ServiceMain(DWORD argc, LPTSTR *argv);
BOOL SendStatusToSCM(DWORD , DWORD , DWORD , DWORD , DWORD );
VOID HandlerEx(DWORD controlCode, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext);
void main(int argc, char* argv[])
{
BOOL success;
SERVICE_TABLE_ENTRY serviceTable[] =
{
{ SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
{ NULL, NULL }
};
//
// Register with the SCM
//
success = StartServiceCtrlDispatcher(serviceTable);
if (!success)
return;
}
// ServiceMain is called when the SCM wants to
// start the service. When it returns, the service
// has stopped. It therefore waits on an event
// just before the end of the function, and
// that event gets set when it is time to stop.
// It also returns on any error because the
// service cannot start if there is an error.
VOID ServiceMain(DWORD argc, LPTSTR *argv)
{
BOOL success;
DWORD dwNum = 0;
MyServiceStatus.dwCurrentState = SERVICE_RUNNING;
serviceStatusHandle = RegisterServiceCtrlHandlerEx(SERVICE_NAME,
(LPHANDLER_FUNCTION_EX)HandlerEx, NULL);
if (!serviceStatusHandle) {terminate(GetLastError()); return;}
// create the termination event
terminateEvent = CreateEvent (0, TRUE, FALSE, 0);
if (!terminateEvent) {terminate(GetLastError()); return;}
// Start the service itself
success = InitService();
if (!success) {terminate(GetLastError()); return;}
// The service is now running.
// Notify SCM of progress
MyServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP
| SERVICE_ACCEPT_SHUTDOWN
| SERVICE_ACCEPT_PAUSE_CONTINUE;
success = SendStatusToSCM(SERVICE_RUNNING, 0, 0, 0, 0);
if (!success) {terminate(GetLastError()); return;}
MyServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP
| SERVICE_ACCEPT_SHUTDOWN
| SERVICE_ACCEPT_PAUSE_CONTINUE
| SERVICE_ACCEPT_SESSIONCHANGE;
success = SendStatusToSCM(SERVICE_RUNNING, 0, 0, 0, 0);
// Wait for stop signal, and then terminate
WaitForSingleObject (terminateEvent, INFINITE);
terminate(0);
}
// This function consolidates the activities of
// updating the service status with SetServiceStatus.
BOOL SendStatusToSCM(DWORD dwCurrentState,
DWORD dwWin32ExitCode,
DWORD dwServiceSpecificExitCode,
DWORD dwCheckPoint,
DWORD dwWaitHint)
{
BOOL success;
DWORD dwNum = 0;
// Fill in all of the SERVICE_STATUS fields
MyServiceStatus.dwServiceType = SERVICE_WIN32;
MyServiceStatus.dwCurrentState = dwCurrentState;
// Set the control codes the service can receive from SCM.
// Make sure that the code contains SERVICE_ACCEPT_SESSIONCHANGE.
// So service will can accept winlogon message.
/*if (dwCurrentState == SERVICE_START_PENDING)
MyServiceStatus.dwControlsAccepted = 0;
else
MyServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN|
SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SESSIONCHANGE; */
// if a specific exit code is defined, set up
// the win32 exit code properly
if (dwServiceSpecificExitCode == 0)
MyServiceStatus.dwWin32ExitCode = dwWin32ExitCode;
else
MyServiceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
MyServiceStatus.dwServiceSpecificExitCode = dwServiceSpecificExitCode;
MyServiceStatus.dwCheckPoint = dwCheckPoint;
MyServiceStatus.dwWaitHint = dwWaitHint;
// Pass the status record to the SCM
success = SetServiceStatus (serviceStatusHandle, &MyServiceStatus);
return success;
}
DWORD ServiceThread(LPDWORD param)
{
while(1)
{
Sleep(1000);
}
return 0;
}
// Initializes the service. Start a new thread
BOOL InitService()
{
DWORD id = 0;
int iTime = 0;
// Start the service's thread
while(NULL == threadHandle && iTime++ < 10)
{
threadHandle = CreateThread(0, 0,
(LPTHREAD_START_ROUTINE) ServiceThread,//callback function.
0, 0, &id );
}
if (threadHandle==0)
return FALSE;
else
{
runningService = TRUE;
return TRUE;
}
}
// Log..
void Log(LPCTSTR msg)
{
#define LOGFILE_PATH TEXT("C:/Log.txt")
HANDLE h = CreateFile(LOGFILE_PATH,
GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_ALWAYS, 0, 0);
if (GetFileSize(h,NULL)==0)
{
byte b[2]={0xFF,0xFE};
DWORD cb = 2;
WriteFile(h, b, 2, &cb, 0);
}
if (INVALID_HANDLE_VALUE != h)
{
if (INVALID_SET_FILE_POINTER != SetFilePointer(h, 0, 0, FILE_END)) {
DWORD cb = lstrlen(msg) * sizeof *msg;
WriteFile(h, msg, cb, &cb, 0);
}
CloseHandle(h);
}
}
// Dispatches events received from the SCM
VOID HandlerEx(DWORD controlCode,
DWORD dwEventType,
LPVOID lpEventData,
LPVOID lpContext)
{
DWORD currentState = 0;
BOOL success;
DWORD dwNum = 0;
CHAR *tszWrite = NULL;
switch(controlCode)
{
case SERVICE_CONTROL_STOP:
// Stop the service
MyServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP
| SERVICE_ACCEPT_SHUTDOWN
| SERVICE_ACCEPT_PAUSE_CONTINUE;
success = SendStatusToSCM(SERVICE_STOP_PENDING, NO_ERROR, 0, 1, 5000);
runningService=FALSE;
SetEvent(terminateEvent);
return;
case SERVICE_CONTROL_PAUSE:
// Pause the service
if (runningService && !pauseService)
{
success = SendStatusToSCM(SERVICE_PAUSE_PENDING, NO_ERROR, 0, 1, 1000);
pauseService = TRUE;
SuspendThread(threadHandle);
currentState = SERVICE_PAUSED;
}
break;
case SERVICE_CONTROL_CONTINUE:
// Resume from a pause
if (runningService && pauseService)
{
success = SendStatusToSCM(SERVICE_CONTINUE_PENDING, NO_ERROR, 0, 1, 1000);
pauseService=FALSE;
ResumeThread(threadHandle);
currentState = SERVICE_RUNNING;
}
break;
case SERVICE_CONTROL_SESSIONCHANGE:
switch(dwEventType)
{
case WTS_SESSION_LOGOFF:
// Logoff
Log("Logoff event happened!");
break;
default:
break;
}
break;
case SERVICE_CONTROL_SHUTDOWN:
// Do nothing in a shutdown. Could do cleanup
// here but it must be very quick.
return;
default:
break;
}
SendStatusToSCM(currentState, NO_ERROR, 0, 0, 0);
}
//
// Handle an error and stop service.
//
VOID terminate(DWORD error)
{
// Close terminateEvent.
if (terminateEvent) CloseHandle(terminateEvent);
// Send a message to the SCM to stop service.
if (serviceStatusHandle)
SendStatusToSCM(SERVICE_STOPPED, error, 0, 0, 0);
// Close thread.
if (threadHandle) CloseHandle(threadHandle);
}
{
if (command != 13)
{
this.ServiceCommandCallback(command);
}
else
{
try
{
PowerBroadcastStatus powerStatus = (PowerBroadcastStatus) eventType;
bool flag = this.OnPowerEvent(powerStatus);
this.WriteEventLogEntry(Res.GetString("PowerEventOK"));
if (!flag)
{
return 0x424d5144;
}
}
catch (Exception exception)
{
this.WriteEventLogEntry(Res.GetString("PowerEventFailed", new object[] { exception.ToString() }), EventLogEntryType.Error);
}
}
return 0;
}
private unsafe void ServiceCommandCallback(int command)
{
fixed (NativeMethods.SERVICE_STATUS* service_statusRef = &this.status)
{
if (command == 4)
{
NativeMethods.SetServiceStatus(this.statusHandle, service_statusRef);
}
else if (((this.status.currentState != 5) && (this.status.currentState != 2)) && ((this.status.currentState != 3) && (this.status.currentState != 6)))
{
switch (command)
{
case 1:
{
int currentState = this.status.currentState;
if ((this.status.currentState == 7) || (this.status.currentState == 4))
{
this.status.currentState = 3;
NativeMethods.SetServiceStatus(this.statusHandle, service_statusRef);
this.status.currentState = currentState;
new DeferredHandlerDelegate(this.DeferredStop).BeginInvoke(null, null);
}
goto Label_0259;
}
case 2:
if (this.status.currentState == 4)
{
this.status.currentState = 6;
NativeMethods.SetServiceStatus(this.statusHandle, service_statusRef);
new DeferredHandlerDelegate(this.DeferredPause).BeginInvoke(null, null);
}
goto Label_0259;
case 3:
if (this.status.currentState == 7)
{
this.status.currentState = 5;
NativeMethods.SetServiceStatus(this.statusHandle, service_statusRef);
try
{
this.OnContinue();
this.WriteEventLogEntry(Res.GetString("ContinueSuccessful"));
}
catch (Exception exception)
{
this.WriteEventLogEntry(Res.GetString("ContinueFailed", new object[] { exception.ToString() }), EventLogEntryType.Error);
this.status.currentState = 7;
goto Label_0259;
}
this.status.currentState = 4;
NativeMethods.SetServiceStatus(this.statusHandle, service_statusRef);
}
goto Label_0259;
case 5:
try
{
this.OnShutdown();
this.WriteEventLogEntry(Res.GetString("ShutdownOK"));
}
catch (Exception exception2)
{
this.WriteEventLogEntry(Res.GetString("ShutdownFailed", new object[] { exception2.ToString() }), EventLogEntryType.Error);
}
goto Label_0259;
}
try
{
this.OnCustomCommand(command);
this.WriteEventLogEntry(Res.GetString("CommandSuccessful"));
}
catch (Exception exception3)
{
this.WriteEventLogEntry(Res.GetString("CommandFailed", new object[] { exception3.ToString() }), EventLogEntryType.Error);
}
}
}
Label_0259:;
}
從上面的代碼可以知道,只有當服務控制碼command不等於13的時候,我們纔有機會用ServiceCommandCallback對其進行處理。而這種處理只能獲得控制碼command,對於SERVICE_CONTROL_SESSIONCHANGE(14)的消息來說,ServiceBase類沒有辦法獲得到底是Logon,Logoff或是用戶切換時候發生的。
因此對於以下C++代碼是沒有辦法移植到Framework 1.1 上的:
DWORD dwEventType,
LPVOID lpEventData,
LPVOID lpContext)
{
...
case SERVICE_CONTROL_SESSIONCHANGE:
switch(dwEventType)
{
case WTS_SESSION_LOGOFF:
// Logoff
ICSEventLogoff();
break;
default:
break;
}
break;
...
}
在.Net Framework 2.0的ServiceBase中,回調函數在接受服務控制命令command之外,還將所有其他參數都傳給了用戶可以自由擴展的回調函數,多了OnSessionChange等包裝好的函數,因此就沒有這個問題了。同樣,我們不用將這個服務用於不支持sessionchange的Win2000上。以下是C#寫的服務:
using System.ServiceProcess;
using System.Text;
using System.IO;
namespace ServiceTest
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
this.CanHandleSessionChangeEvent = true;
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
this.CanHandleSessionChangeEvent = false;
System.IO.FileStream fs = new System.IO.FileStream("c:/mysvc.txt",
System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite);
UTF8Encoding asc = new UTF8Encoding();
String log = "stop ";
fs.Seek(0, System.IO.SeekOrigin.End);
fs.Write(asc.GetBytes(log), 0, asc.GetByteCount(log));
fs.Close();
}
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
base.OnSessionChange(changeDescription);
FileStream fs = new FileStream("c:/Log.txt",
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
UTF8Encoding asc = new UTF8Encoding();
String log = "On Session Change ";
fs.Seek(0, System.IO.SeekOrigin.End);
fs.Write(asc.GetBytes(log), 0, asc.GetByteCount(log));
fs.Close();
}
}
}
安裝服務可以用一個叫SRVINSTW.EXE的小工具,很方便。微軟的instalutil.exe命令行真難用,bs一下。