How to disable and enable a network adapter with Delphi?

Asked

Viewed 612 times

5

I have an application that at some point should disable and enable the Windows network adapter, I searched through the internet, but found nothing.

Test before posting an answer because dubious information only delays my work.

  • I believe WMI is an easier way to go if performance isn’t so necessary for you. Not that WMI is slow, but... it is slower than working with the network interface via classic WINAPI. The class in question is that one

  • Managed to solve @Pascal?

  • @Pascalstarting if I could help with my answer, you can accept the answer by clicking on the left side of it. If you need any more help, let us know

1 answer

3

Through the following code is possible enable and disable a no choice network card, sending commands to the command line and treating its output, I tried to detail everything that happens in the code to understand the steps:

Procedure TfrmMain.ResetNetwork;
var i, APos: Integer;
    ALine, AIndex, AName: String;
begin
  //pega todas as redes do pc
  Memo1.Text := Memo1.Text + GetDosOutput('wmic nic get name, index');
  Application.ProcessMessages;

  //vai ler todas linhas do memo uma a uma
  for i := 0 to Memo1.Lines.Count - 1 do
    Begin
      //passa a linha para uma variavel
      //exemplo da linha pretendida:
      //"0      Microsoft Kernel Debug Network Adapter"
      ALine := AnsiUpperCase(Memo1.Lines[i]);    

      //pega o valor "index 
      APos := Pos(' ', ALine);
      if (APos > 0) then
        begin
          AIndex := Trim(AnsiMidStr(ALine, 1, APos - 1));
          Delete(ALine, 1, APos);
        end;

      //verifica se o valor "name" é igual ao pretendido
      if AnsiLeftStr(Trim(ALine), 38) = 'MICROSOFT KERNEL DEBUG NETWORK ADAPTER' then
        Begin
          //se o valor for igual passa aqui
          Memo1.Lines.Add('DISABLE index: ' + AIndex);
          //aqui desabilita
          GetDosOutput('wmic path win32_networkadapter where index='+ AIndex +' call disable');
          Application.ProcessMessages;
          sleep(2000);
          Memo1.Lines.Add('ENABLE index: ' + AIndex);
          //aqui habilita
          GetDosOutput('wmic path win32_networkadapter where index='+ AIndex +' call enable');
          Application.ProcessMessages;
        End;
    End;
End;

Function TfrmMain.GetDosOutput(CommandLine: string; Work: string = 'C:\'): string;
var SA: TSecurityAttributes;
    SI: TStartupInfo;
    PI: TProcessInformation;
    StdOutPipeRead, StdOutPipeWrite: THandle;
    WasOK: Boolean;
    Buffer: array[0..255] of AnsiChar;
    BytesRead: Cardinal;
    WorkDir: string;
    Handle: Boolean;
begin
  Result := '';
  with SA do
    begin
      nLength := SizeOf(SA);
      bInheritHandle := True;
      lpSecurityDescriptor := nil;
    end;
  CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);
  try
    with SI do
      begin
        FillChar(SI, SizeOf(SI), 0);
        cb := SizeOf(SI);
        dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
        wShowWindow := SW_HIDE;
        hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
        hStdOutput := StdOutPipeWrite;
        hStdError := StdOutPipeWrite;
      end;
    WorkDir := Work;
    Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine), nil, nil, True, 0, nil, PChar(WorkDir), SI, PI);
    CloseHandle(StdOutPipeWrite);
    if Handle then
      try
        repeat
          WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil);
          if BytesRead > 0 then
            begin
              Buffer[BytesRead] := #0;
              Result := Result + Buffer;
            end;
        until not WasOK or (BytesRead = 0);
        WaitForSingleObject(PI.hProcess, INFINITE);
      finally
        CloseHandle(PI.hThread);
        CloseHandle(PI.hProcess);
      end;
  finally
    CloseHandle(StdOutPipeRead);
  end;
end;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.