How to detect network connect/disconnect?  Download
This is a Delphi function that detects network connect or disconnect on the local computer. It is designed for Windows 2000 or higher. This examples utilizes TWmiSystemEvents components. The code below creates and destroys the components on the fly, so this function may be used in console- or UI-type applications. Please note that the event handling in the UI applications is much easier: you just have to drop a component on the form and write an event handler.

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;