我想用软件修改电脑名称后不需要重启电脑就能生效,在网上找到了一段代码套上修改后右键“计算机”属性看到的名称确实变了,但是实际它还没有生效,在cmd里运行"ipconfig /all"的时候还是显示旧的电脑名称,下面附上代码,希望各位大神帮看看。
[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;
namespace 修改电脑名称
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// SendMessageTimeout tools
[Flags]
public enum SendMessageTimeoutFlags : uint
{
SMTO_NORMAL = 0x0000,
SMTO_BLOCK = 0x0001,
SMTO_ABORTIFHUNG = 0x0002,
SMTO_NOTIMEOUTIFNOTHUNG = 0x0008
}
const int WM_SETTINGCHANGE = 0x001A;
const int HWND_BROADCAST = 0xffff;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
IntPtr windowHandle,
uint Msg,
IntPtr wParam,
string lParam,
SendMessageTimeoutFlags flags,
uint timeout,
out IntPtr result
);
public static void NotifyOS1()
{
IntPtr result1;
//修改后发送一个消息给系统
//调用
SendMessageTimeout(
new IntPtr(HWND_BROADCAST),
WM_SETTINGCHANGE,
IntPtr.Zero,
"Environment",
SendMessageTimeoutFlags.SMTO_ABORTIFHUNG,
200,
out result1);
}
private void button1_Click(object sender, EventArgs e)
{
RegistryKey myRKCN = Registry.LocalMachine.OpenSubKey("SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters");
foreach (string myCpName in myRKCN.GetValueNames())
{
if (myCpName == "NV Hostname")
{
this.textBox1.Text = myRKCN.GetValue(myCpName).ToString();
NotifyOS1();
}
else
{
continue;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
RegistryKey myRKCN = Registry.LocalMachine.OpenSubKey("SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters", true);
foreach (string site in myRKCN.GetValueNames())
{
if (site == "NV Hostname")
{
myRKCN.DeleteValue(site, false);
myRKCN.SetValue("NV Hostname", this.textBox1.Text);
}
else
{
continue;
}
}
MessageBox.Show("修改成功");
}
}
}
|