簡體   English   中英

kernel32.dll SetComputerName win32錯誤6

[英]kernel32.dll SetComputerName win32 error 6

我嘗試通過kernel32.dll導入和函數SetComputerName更改主機名。 SetComputerName函數

Mainclass:

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)句柄無效。

不知道手柄出了什么問題。

您只是做錯了。 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM