title: RegOpenKeyEx returns error 161
body: <p>i'm having difficulty to rename one key of my registry. I dont know but all the time change the name so i was trying to use a program to do automatically. The code is the follow:</p>
  
  <pre><code>using Microsoft.Win32;
  using Microsoft.Win32.SafeHandles;
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Runtime.InteropServices;
  using System.Text;
  using System.Threading.Tasks;
  
  namespace ConsoleApplication7
  {
      class Program
      {
          private static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(-2147483646);
          [DllImport("advapi32")]
          public static extern int RegRenameKey(SafeRegistryHandle hKey, [MarshalAs(UnmanagedType.LPWStr)] string oldname,
          [MarshalAs(UnmanagedType.LPWStr)] string newname);
          [DllImport("Advapi32.dll", EntryPoint = "RegOpenKeyExW", CharSet = CharSet.Unicode)]
          public static extern int RegOpenKeyEx(IntPtr hKey, [In] string lpSubKey, int ulOptions, int samDesired, out IntPtr phkResult);
  
          static void Main(string[] args)
          { //mhmmm si, todo esta bien , bueno ire a ver lo que iba oka  ver
              ///Estas intentando renombrar una clave de registro una la crpeta que la contiene...
              IntPtr result;
  
              SafeRegistryHandle hKey = null;//no es necesario, esta funcuonando, si no, no me hubiere retorando un int
              hKey = new SafeRegistryHandle(HKEY_LOCAL_MACHINE,true);
              int resul = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "\\SOFTWARE\\Company", 0,0,out result);
              Console.WriteLine(resul);
              int rosul = RegRenameKey(hKey, "SOFTWARE\\Company\\", "SOFTWARE\\Editado\\");
              Console.WriteLine(rosul);
              Console.ReadLine(); //Ok a ver dejamever unos ejemplos de advapi, los tienes ahi? mierdaaa no tiees ideas de los peos que se acaba de tirar mi perro
  
          }
  
      }
  }
  </code></pre>
  
  <p>The problem is when i open the key:</p>
  
  <pre><code>int resul = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "\\SOFTWARE\\Company", 0,0,out result);
  </code></pre>
  
  <p>For some reason i'm not opening well the key. The error's return me:</p>
  
  <p><a href="https://i.stack.imgur.com/7MLJA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7MLJA.png" alt="errors"></a></p>
  
  <p>My regedit rule is not renamed:</p>
  
  <p><a href="https://i.stack.imgur.com/Roaeo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Roaeo.png" alt="capture of my key"></a></p>
  
  <p>Article that i took like reference:</p>
  
  <p><a href="http://blogs.microsoft.co.il/pavely/2015/09/29/regrenamekey-hidden-registry-api/" rel="nofollow noreferrer">http://blogs.microsoft.co.il/pavely/2015/09/29/regrenamekey-hidden-registry-api/</a></p>
  
  <p>I hope someone helps... It's for my computer only.</p>