// this object is required only in console applications.
// In UI applications the TWmiSystemEvents component can be
// dropped on the form, the event handler will be the form's method.
type
TWaitObject = class
private
FEventHappend: boolean;
private
procedure EventHandler(ASender: TObject; Instance: OleVariant;
ServiceName: widestring; State: widestring; Action: TWmiEventAction);
public
property EventHappend: boolean read FEventHappend;
end;
procedure TWaitObject.EventHandler(ASender: TObject; Instance: OleVariant;
ServiceName: widestring; State: widestring; Action: TWmiEventAction);
begin
case Action of
weaCreated: writeln('New service is installed: '+ServiceName);
weaDeleted: writeln('The service was uninstalled: '+ServiceName);
weaModified: writeln('The service "'+ServiceName +
'" has changed. Its new state is "'+State+'"');
weaUnknown: writeln('Unknown event happened for service '+ServiceName);
end;
end;
// this function monitors the services for a specified time.
// It may be used for local or remote host. When used for local host
// TargetHost, UserName, Password parameters must be empty.
// For remote computer the parameters must be:
// TargetHost: name or IP address of the remote host, like '10.8.36.54'
// UserName: name of the user, may include domain, like 'MOON\Administrator';
// Password: the user's password.
// WaitTimeSeconds: the time after which the monitoring stops.
// Specify -1 to monitor indefinitely
procedure MinitorServices(TargetHost, UserName, Password: string;
WaitTimeSeconds: integer);
var
vWmiEvents: TWmiSystemEvents;
vDeadline: TDateTime;
vWaitObject: TWaitObject;
vTime: double;
const
SECOND = 1/24/60/60;
YEAR = 365;
begin
vTime := WaitTimeSeconds;
if WaitTimeSeconds >= 0 then vDeadline := Now + (vTime) * SECOND
else vDeadline := Now + 1000 * YEAR;
// setup: create and link the components together
vWaitObject := TWaitObject.Create;
vWmiEvents := TWmiSystemEvents.Create(nil);
try
vWmiEvents.MachineName := TargetHost;
vWmiEvents.Credentials.UserName := UserName;
vWmiEvents.Credentials.Password := Password;
vWmiEvents.PoolingInterval := 100;
vWmiEvents.OnService := vWaitObject.EventHandler;
// try to activate. It may fail if the computer does not have
// WMI (like windows 95, 98, NT without WMI core installed)
try
vWmiEvents.Active := true;
except
on E: Exception do
begin
writeln('cannot connect to WMI service. '+E.Message);
Exit;
end;
end;
while (Now < vDeadline) do
begin
Sleep(100);
Application.ProcessMessages;
CheckSynchronize; // let background threads to wake up.
end;
finally
vWmiEvents.Free;
vWaitObject.Free;
end;
end;
|