1

我尝试通过 kernel32.dll 导入和函数 SetComputerName 更改主机名。设置计算机名称函数

主类:

namespace Castell
{
  class Program
  {
      private static string hostname { get; set; }
      setHostname();
      private static void setHostname()
      {
         hostname = "TEST123456789";
         int errorcode = ImportDLL.SetComputerName(hostname);
         Console.WriteLine(Marshal.GetLastWin32Error());
      }
  }
}

导入类:

namespace Castell
{
    class ImportDLL
    {
        [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int SetComputerName(string hostname);
    }
}

Marshal.GetLastWin32Error() 的结果是“6”。这意味着: ERROR_INVALID_HANDLE 6 (0x6) 句柄无效。

不知道手柄有什么问题。

4

1 回答 1

1

你只是做错了。SetComputerName() 的返回类型是 bool,而不是 int。函数失败时返回false 。winapi 中的硬性规则是,您应该只在函数失败时获取错误代码。或者换一种说法,当函数成功时,Windows 不会显式地将错误代码设置回 0。然后才使用Marshal.GetLastWin32Error() 来检索错误代码。否则由 Win32Exception 类构造函数自动完成。这使得这段代码工作:

  public static void SetHostname(string hostname)
  {
     if (!SetComputerName(hostname)) {
         throw new System.ComponentModel.Win32Exception();
     }
  }

  [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  private static extern int SetComputerName(string hostname);
于 2013-11-18T15:29:51.307 回答