Question

I have a delphi program that is used in multiple stores. These stores all connect to an online mysql database. On the application start up, the program connects to the database. The program was freezing when the computer was not connected to the internet. I found this below procedure that tests if the computer is connected to the internet:

public
function IsConnectedToInternet: Boolean;   

const
  INTERNET_CONNECTION_MODEM = 1;
  INTERNET_CONNECTION_LAN = 2;
  INTERNET_CONNECTION_PROXY = 4;
  INTERNET_CONNECTION_MODEM_BUSY = 8; 

implementation

function InternetGetConnectedState(lpdwFlags: LPDWORD;
dwReserved: DWORD): BOOL; stdcall; external 'WININET.DLL';

function TForm1.IsConnectedToInternet: Boolean;
var
dwConnectionTypes: Integer;
begin
  try
    dwConnectionTypes := INTERNET_CONNECTION_MODEM +
    INTERNET_CONNECTION_LAN +
    INTERNET_CONNECTION_PROXY;

    if InternetGetConnectedState(@dwConnectionTypes, 0) then
      Result := true
    else
      Result := false;
  except
    Result := false;
  end;
end;

procedure Tform1.FormCreate(Sender: TObject);
begin
  If IsConnectedToInternet then
    MysqlConnection.Connect;
end;

This works fine in testing if the computer is connected to the wifi etc.. But it does not test if this connection has internet access. Example if the computer is connected to a wifi which has a limit of 10gb and when that 10gb is used up, the computer will still be connected to the wifi but will not have internet access.

In this case the above function will give a result of true making the program try to connect and this will make the program freeze.

How do i resolve this error? Is there a procedure that tests if the computer has internet access?

Was it helpful?

Solution

The only reliable way to check connectivity is to attempt to connect. Doing so can block the thread which attempts to connect. The logical conclusion then is that to stop the UI thread from being blocked, you must connect from a thread other than the UI thread.

OTHER TIPS

Add in your uses the unit "WinNet". With the function "InternetGetConnectedState" return a value for internet state and type. See below:

    function YourFunctionName : boolean;
  var
     origin : cardinal;
  begin
     result := InternetGetConnectedState(@origin,0);

     //connections origins by origin value
     //NO INTERNET CONNECTION              = 0;
     //INTERNET_CONNECTION_MODEM           = 1;
     //INTERNET_CONNECTION_LAN             = 2;
     //INTERNET_CONNECTION_PROXY           = 4;
     //INTERNET_CONNECTION_MODEM_BUSY      = 8;
  end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top