type
TWaitTarget = (CONNECT, DISCONNECT, UNKNOWN);
// 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.
TWaitObject = class
private
FEventHappend: boolean;
private
procedure EventHandler(AObject: TObject);
public
property EventHappend: boolean read FEventHappend;
end;
procedure TWaitObject.EventHandler(AObject: TObject);
begin
FEventHappend := true;
end;
// this function waits for docking/undocking event for specified time.
// it returns true if the event happed and false if the specified
// time elapsed.
function WaitForNetworkEvent(WaitTimeMillisec: integer; WaitFor: TWaitTarget): boolean;
var
vWmiEvents: TWmiSystemEvents;
vDeadline: TDateTime;
vWaitObject: TWaitObject;
vTime: double;
const
SECOND = 1/24/60/60;
begin
Result := false;
vTime := WaitTimeMillisec;
vDeadline := Now + (vTime/1000) * SECOND;
// setup: create and link the components together
vWaitObject := TWaitObject.Create;
vWmiEvents := TWmiSystemEvents.Create(nil);
try
vWmiEvents.PoolingInterval := 100;
case WaitFor of
CONNECT: vWmiEvents.OnNetworkConnect := vWaitObject.EventHandler;
DISCONNECT: vWmiEvents.OnNetworkDisconnect := vWaitObject.EventHandler;
end;
// 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
Exit;
end;
while Now < vDeadline do
if vWaitObject.EventHappend then
begin
Result := true;
Exit;
end else
begin
Sleep(100);
Application.ProcessMessages;
CheckSynchronize; // let background threads to wake up.
end;
finally
vWmiEvents.Free;
vWaitObject.Free;
end;
end;
|