الخميس، 15 ديسمبر 2011

C#: Set And Unset Auto-start For Windows Application


I found this useful C# class in this MSDN forum that provides an easy way to enable and disable an application auto-run in Windows.
With a little modification,  to be easily called by any project. What you need to do is just pass in the 'Key Name' and 'Assembly Location' parameters.


Here is the complete class

using Microsoft.Win32;

///


/// Utility.
///


public class Util
{
private const string RUN_LOCATION = @"Software\Microsoft\Windows\CurrentVersion\Run";

///

/// Sets the autostart value for the assembly.
///


/// Registry Key Name
/// Assembly location (e.g. Assembly.GetExecutingAssembly().Location)
public static void SetAutoStart(string keyName, string assemblyLocation)
{
RegistryKey key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION);
key.SetValue(keyName, assemblyLocation);
}

///

/// Returns whether auto start is enabled.
///


/// Registry Key Name
/// Assembly location (e.g. Assembly.GetExecutingAssembly().Location)
public static bool IsAutoStartEnabled(string keyName, string assemblyLocation)
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(RUN_LOCATION);
if (key == null)
return false;

string value = (string)key.GetValue(keyName);
if (value == null)
return false;

return (value == assemblyLocation);
}

///

/// Unsets the autostart value for the assembly.
///


/// Registry Key Name
public static void UnSetAutoStart(string keyName)
{
RegistryKey key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION);
key.DeleteValue(keyName);
}
}
Sample Usage:

string keyName = "MyProgramName";
string assemblyLocation = Assembly.GetExecutingAssembly().Location;  // Or the EXE path.

// Set Auto-start.
Util.SetAutoStart(keyName, assemblyLocation);

// Unset Auto-start.
if (Util.IsAutoStartEnabled(keyName, assemblyLocation))
    Util.UnSetAutoStart(keyName);
Originally Posted by:- 
http://simpcode.blogspot.com/2008/07/c-set-and-unset-auto-start-for-windows.html

ليست هناك تعليقات:

إرسال تعليق

كل ما تريد معرفته عن فيتامين "لاكتوفيرين"

ماهو اللاكتوفيرين ؟ يعتبر اللاكتوفيرين بروتين طبيعي موجود في الحليب الحيواني للأبقار وكذلك يتواجد في حليب الأمهات في الإنسان، ويتواجد بكثر...