Codigo c#
//Variables string lbl = ""; string path = ""; //NombreApp será el identificador en el registrostring nombreApp = "";
//Evento load del formulario private void Formulario_Load(object sender, EventArgs e) { lbl = Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6) + "\\" + lbl; nombreApp = "MiAplicacion"; }
Ahora en el botón btnInicio realizaremos el siguiente código :
// Resgistrará en Inicio del registro la aplicación indicada // Devuelve True si todo fue bien, False en caso contrario // Guardar la clave en el registro // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run try { RegistryKey runK = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); // añadirlo al registro // Si el path contiene espacios se debería incluir entre comillas dobles if (nombreApp.StartsWith("\"") == false && nombreApp.IndexOf(" ") > -1) { nombreApp = "\"" + nombreApp + "\""; } runK.SetValue(path, nombreApp); return true; } catch (Exception ex) { Console.WriteLine("ERROR al guardar en el registro.{0}Seguramente no tienes privilegios suficientes.{0}{1}{0}---xxx---{2}", '\n', ex.Message, ex.StackTrace); return false; }
Y finalmente en el boton btnNoInicio el siguiente codigo :
// Quitará de Inicio la aplicación indicada // Devuelve True si todo fue bien, False en caso contrario // Si la aplicación no estaba en Inicio, devuelve True salvo que se produzca un error try { RegistryKey runK = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); // quitar la clave indicada del registo runK.DeleteValue(path, false); return true; } catch (Exception ex) { Console.WriteLine("ERROR al eliminar la clave del registro.{0}Seguramente no tienes privilegios suficientes.{0}{1}{0}---xxx---{2}", '\n', ex.Message, ex.StackTrace); return false; }
Espero les haya sido útil. Saludos!.
No hay comentarios:
Publicar un comentario