This example implements the functions of C# changing IP with one click, resetting DNS, gateway and mask. The specific functions are to set the IP address and subnet mask in the program interface window, set the gateway address, and set DNS. During the setting process, the program will judge that if there is no network device with IP settings enabled, skip it, reset DNS to empty, and enable DHCP.
The main function codes are as follows:
using System; using ; using ; using ; using ; using ; using ; using ; namespace changeIP { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { ManagementBaseObject inPar = null; ManagementBaseObject outPar = null; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = (); foreach (ManagementObject mo in moc) { if (!(bool)mo["IPEnabled"]) continue; //Set the IP address and subnet mask inPar = ("EnableStatic"); string ip = ""; ip = () + "." + () + "." + () + "." + (); inPar["IPAddress"] = new string[] { ip };// 1. Backup string ym = ""; ym = () + "." + () + "." + () + "." + (); inPar["SubnetMask"] = new string[] { ym }; outPar = ("EnableStatic", inPar, null); //Set the gateway address inPar = ("SetGateways"); string wg = ""; wg = () + "." + () + "." + () + "." + (); inPar["DefaultIPGateway"] = new string[] { wg }; // 1. Gateway; 2. Backup Gateway outPar = ("SetGateways", inPar, null); //Set DNS inPar = ("SetDNSServerSearchOrder"); string dns1 = () + "." + () + "." + () + "." + (); string dns2 = () + "." + () + "." + () + "." + (); inPar["DNSServerSearchOrder"] = new string[] { dns1, dns2 }; // 2. Alternate DNS outPar = ("SetDNSServerSearchOrder", inPar, null); break; } } private void button2_Click(object sender, EventArgs e) { ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = (); foreach (ManagementObject mo in moc) { // If there is no network device with IP settings enabled, skip if (!(bool)mo["IPEnabled"]) continue; //Reset DNS to empty ("SetDNSServerSearchOrder", null); //Open DHCP ("EnableDHCP", null); } } private void button3_Click(object sender, EventArgs e) { (); (); } private void Form1_KeyDown(object sender, KeyEventArgs e) { switch () { case Keys.F2: button1_Click(sender, e); break; case Keys.F3: button2_Click(sender, e); break; } } } }