首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 開發 IP 設定快速切換工具:netsh 命令自動化網路設定檔

     編輯:Delphi

原理

Windows netsh 命令可匯出/匯入網路設定:

  • netsh interface dump > netcfg.txt:將目前介面設定 (IP、閘道、DNS、WINS 等) 導出文字檔。
  • netsh -f netcfg.txt:套用設定檔,即時切換網路環境。

程式架構

  1. 介面:兩組 IP 設定編輯區 (介面、IP、子網路遮罩、閘道、DNS),分別對應「公司網路」、「家用/無線網路」。
  2. 「儲存設定」按鈕:呼叫 netsh interface dump 導出目前設定,再手動修正關鍵欄位 (IP、Gateway、DNS) 寫入專屬設定檔 (netcfg1.txt、netcfg2.txt)。
  3. 「套用切換」按鈕:WinExec('netsh -f netcfg1.txt', SW_HIDE) 無訊息套用。

核心程式碼

procedure TForm1.SaveProfile(const ProfileName: string; IsProfile1: Boolean);
var
  DumpFile, CfgFile: string;
  SL: TStringList;
  i: Integer;
  Line: string;
begin
  DumpFile := 'temp_dump.txt';
  CfgFile := IfThen(IsProfile1, 'netcfg1.txt', 'netcfg2.txt');

  // 1. 導出目前完整設定
  WinExec(PChar('cmd /c netsh interface dump > ' + DumpFile), SW_HIDE);
  Sleep(500); // 等待命令完成

  // 2. 讀取並替換關鍵欄位
  SL := TStringList.Create;
  try
    SL.LoadFromFile(DumpFile);
    for i := 0 to SL.Count - 1 do
    begin
      Line := SL[i];
      if Line.StartsWith('set address') then
        Line := Format('set address name="%s" source=static addr=%s mask=%s gateway=%s gwmetric=1',
          [edtInterface.Text, edtIP.Text, edtMask.Text, edtGateway.Text])
      else if Line.StartsWith('set dnsservers') then
        Line := Format('set dnsservers name="%s" source=static addr=%s register=PRIMARY',
          [edtInterface.Text, edtDNS.Text]);
      SL[i] := Line;
    end;
    SL.SaveToFile(CfgFile);
  finally
    SL.Free;
  end;
  DeleteFile(DumpFile);
end;

procedure TForm1.ApplyProfile(IsProfile1: Boolean);
var
  CfgFile: string;
begin
  CfgFile := IfThen(IsProfile1, 'netcfg1.txt', 'netcfg2.txt');
  if FileExists(CfgFile) then
    WinExec(PChar('netsh -f ' + CfgFile), SW_HIDE)
  else
    ShowMessage('設定檔不存在,請先儲存');
end;

IP 輸入驗證 (MaskEdit)

procedure TForm1.MaskEditIPExit(Sender: TObject);
var
  Parts: TArray;
  Octet: Integer;
begin
  Parts := MaskEditIP.Text.Split(['.']);
  if Length(Parts) <> 4 then RaiseError;
  for Octet in Parts do
  begin
    if not TryStrToInt(Octet, Octet) or (Octet < 0) or (Octet > 255) then
      RaiseError;
  end;
end;

現代化改進建議

  • 使用 WMI (Win32_NetworkAdapterConfiguration) 或 NetShell API (INetSh) 直接程式化設定,避免命令列解析與權限問題。
  • 需管理員權限執行 (Manifest requireAdministrator)。
  • 支援 IPv6、多網卡、DHCP/靜態切換、DNS 多組、介面別名 (介面名稱可能含空白需加引號)。
  • 介面採用 TComboBox 列舉現有網卡 (GetAdaptersInfo),避免手動輸入介面名稱。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved