How to handle sleep mode network loss with database applications

delphi, delphi-xe2, networking

Solution

To elaborate on RRUZ, you want something like:

procedure WMPowerBroadcast(var AMessage: TMessage); message WM_POWERBROADCAST;

in your form. Then `WMPowerBroadcast` will be something like:

procedure TMyForm.WMPowerBroadcast(var AMessage: TMessage);
const
  PBT_APMSUSPEND = 4;
  PBT_APMRESUMESUSPEND = 7;
begin
  case AMessage.WParam of
    PBT_APMSUSPEND:
    begin
      // save your DB stuff. NOTE: IIRC you are pretty limited in the time 
      // you get to do this - 2 seconds ? may be the limit
    end;
    PBT_APMRESUMESUSPEND:
    begin
      // restore your DB connection
    end;
  else
     // you're going to want to handle PBT_APMRESUMECRITICAL (XP and older systems) and PBT_APMRESUMEAUTOMATIC differently
     // IIRC you did not get notification of the suspend in this case
  end;
end;

Problem

I have several Delphi programs that maintain connections to a database (some Oracle, some Firebird.) If the program are running while Windows goes into sleep mode the connection to the database is lost. What's the best way to handle this situation? Is there some way to receive an event before the network goes into sleep mode so I can attempt to handle the situation better?

Original source