MainForm.cs

 //
// Copyright © 2006 Herbert N Swearengen III (hswear3@swbell.net)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   - Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   - Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
// OF SUCH DAMAGE.
//

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Windows.Forms;
using Microsoft.Win32;

namespace StartupManager
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        private NativeMethods native = new NativeMethods();
        private System.Resources.ResourceManager ResourceManager =
            new System.Resources.ResourceManager("StartupManager.Properties.Resources", typeof(MainForm).Assembly);

        #region Constants and Variables

        private const string runKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
        private string allUsersStartup = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"";
        private string currentUserStartup = Environment.GetFolderPath(Environment.SpecialFolder.Programs) + @"\Startup";
        private int i;                  // Counter for registry startup entries.
        private bool ascending;         // Used to toggle column sort.
        private int currentIndex;       // Index of entry that is currently selected.
        private bool admin;             // True if user has administrative privileges.

        // Listview column constants.
        private enum ListCol
        {
            ItemName = 0,
            FileName = 1,
            Type = 2,
            Status = 3,
            Command = 4,
            Path = 5
        }

        // Shortcut type (location) constants.
        private const string HKCU = "Registry: Current User";
        private const string HKLM = "Registry: All Users";
        private const string StartupCurrentUser = "Startup Folder: Current User";
        private const string StartupAllUsers = "Startup Folder: All Users";

        #endregion

        #region MainForm Events

        private void MainForm_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                // Get user privilege level.
                WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
        admin = wp.IsInRole(WindowsBuiltInRole.Administrator);

                if (!admin)
                {
                    // Display message if user is not an administrator.
                    DialogResult result = MessageBox.Show(
                        "To be able to change all startup items you must run this program as an administrator.\r\n" +
                        "If you continue, you will only be able to change those items marked "Current User"\r\n" +
                        "Do you wish to continue?", Application.ProductName,
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

                    // Exit if user does not want to continue as a non-admin.
                    if (result == DialogResult.No)
                    {
                        Application.Exit();
                    }
                }

                // Display startup items.
                FillListview();
            }
            catch (Win32Exception ex)
            {
                MessageBox.Show("An error has occurred in " + Application.ProductName + "\r\n" +
                    "Description: " + ex.Message,
                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (SecurityException exc)
            {
                MessageBox.Show("An error has occurred in " + Application.ProductName + "\r\n" +
                    "Description: " + exc.Message,
                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        void MainForm_Resize(object sender, System.EventArgs e)
        {
            // Resize listview columns based upon new form width.
            listviewStartup.Columns[0].Width = (int)Math.Round(listviewStartup.Width * .347, 0);
            listviewStartup.Columns[1].Width = (int)Math.Round(listviewStartup.Width * .296, 0);
            listviewStartup.Columns[2].Width = (int)Math.Round(listviewStartup.Width * .238, 0);
            listviewStartup.Columns[3].Width = (int)Math.Round(listviewStartup.Width * .090, 0);
        }

        #endregion

        #region ListView Events

        private void listviewStartup_ItemSelectionChanged(object sender,
            ListViewItemSelectionChangedEventArgs e)
        {
            try
            {
                if (e.IsSelected)
                {
                    // Make the selected index available.
                    currentIndex = e.ItemIndex;

                    // Get command and file path stored in listview and make available panel wide.
                    string command = listviewStartup.Items[e.ItemIndex].SubItems[(int)ListCol.Command].Text;
                    string filePath = listviewStartup.Items[e.ItemIndex].SubItems[(int)ListCol.Path].Text;
                   
                    // Determine if file has hidden or system attribute.
                    if (((File.GetAttributes(filePath) & FileAttributes.Hidden) == FileAttributes.Hidden) ||
                       ((File.GetAttributes(filePath) & FileAttributes.System) == FileAttributes.System))
                    {
                        // Change to normal.
                        File.SetAttributes(filePath, FileAttributes.Normal);
                    }
                   
                    // Display the file information.
                    if (filePath.Contains("cmd.exe"))
                    {
                        // Since this is a command window, we will not be able to resolve any properties.
                        labelCompany.Text = "";
                        labelProductName.Text = "";
                        labelDescription.Text = "";
                        labelFileVersion.Text = "";
                        labelCommand.Text = command;

                        // Only display arguments for shortcuts.
                        labelArguments.Visible = false;
                        labelArgumentsDesc.Visible = false;
                        labelArguments.Text = "";
                    }
                    else if (Path.GetExtension(filePath) == ".lnk" || Path.GetExtension(filePath) == ".disabled")
                    {
                        // Resolve the shortcut.
                        ShortcutClass sc = new ShortcutClass(filePath);

                        // Get the file version information.
                        FileVersionInfo selectedFileVersionInfo = FileVersionInfo.GetVersionInfo(sc.Path);

                        // Display the resolved shortcut properties.
                        labelCompany.Text = selectedFileVersionInfo.CompanyName;
                        labelProductName.Text = selectedFileVersionInfo.ProductName;
                        labelDescription.Text = selectedFileVersionInfo.FileDescription;
                        labelFileVersion.Text = selectedFileVersionInfo.FileVersion;
                        labelCommand.Text = sc.Path;

                        // Display arguments for shortcuts, but only if present.
                        if (string.IsNullOrEmpty(sc.Arguments))
                        {
                            labelArgumentsDesc.Visible = false;
                            labelArguments.Visible = false;
                        }
                        else
                        {
                            labelArguments.Visible = true;
                            labelArgumentsDesc.Visible = true;
                            labelArguments.Text = sc.Arguments;
                        }

                        // Dispose of the class instance.
                        sc.Dispose();
                    }
                    else
                    {
                        // Get the file version information.
                        FileVersionInfo selectedFileVersionInfo =
                            FileVersionInfo.GetVersionInfo(filePath);

                        // Display the file properties.
                        labelCompany.Text = selectedFileVersionInfo.CompanyName;
                        labelProductName.Text = selectedFileVersionInfo.ProductName;
                        labelDescription.Text = selectedFileVersionInfo.FileDescription;
                        labelFileVersion.Text = selectedFileVersionInfo.FileVersion;
                        labelCommand.Text = command;

                        // Only display arguments for shortcuts.
                        labelArguments.Visible = false;
                        labelArgumentsDesc.Visible = false;
                        labelArguments.Text = "";
                    }
               
                }

                // Set state of context menu and tool strip buttons depending upon location and user rights.
                if (listviewStartup.Items[e.ItemIndex].SubItems[(int)ListCol.Type].Text.Contains("Current User"))
                {
                    SetItems(e.ItemIndex, "Current User");
                }
                else if (listviewStartup.Items[e.ItemIndex].SubItems[(int)ListCol.Type].Text.Contains("All Users"))
                {

                    // Do not allow non admins to do anything in All Users.
                    if (admin == false)
                    {
                        toolStripMenuItemEnable.Enabled = false;
                        toolStripButtonEnable.Enabled = false;
                        toolStripMenuItemDisable.Enabled = false;
                        toolStripButtonDisable.Enabled = false;
                        toolStripMenuItemDelete.Enabled = false;
                        toolStripButtonDelete.Enabled = false;
                        toolStripMenuItemExecute.Enabled = false;
                        toolStripButtonExecute.Enabled = false;
                        toolStripMenuItemOpen.Enabled = false;
                        toolStripButtonOpen.Enabled = false;
                        toolStripMenuItemMoveToAllUsers.Enabled = false;
                        toolStripButtonMoveToAllUsers.Enabled = false;
                        toolStripMenuItemMoveToCurrentUser.Enabled = false;
                        toolStripButtonMoveToCurrentUser.Enabled = false;
                    }
                    else
                    {
                        SetItems(e.ItemIndex, "All Users");
                    }
                }
            }
            catch (SecurityException ex)
            {
                MessageBox.Show("You do not have permission to view the properties of this file." + "\r\n" +
                    "The system returned the following information:" + "\r\n" +
                    "Description: " + ex.Message, Application.ProductName, MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
            catch (FileNotFoundException)
            {
                MessageBox.Show("The file was not found or is hidden.", Application.ProductName,
                    MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }

        }

        /// <summary>
        /// Set the ListViewItemSorter property to a new ListViewItemComparer
        /// object. Setting this property immediately sorts the
        /// ListView using the ListViewItemComparer object.
        /// </summary>
        private void listviewStartup_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
        {
            // Toggle sort order.
            if (ascending == false)
            {
                ascending = true;
            }
            else
            {
                ascending = false;
            }

            // Perform sort of items in specified column.
            listviewStartup.ListViewItemSorter = new ListViewItemComparer(e.Column, ascending);

        }

        #endregion

        #region Main Tool Strip Menu Events

        private void toolStripMenuItemExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripMenuItemAbout_Click(object sender, EventArgs e)
        {
            AboutForm about = new AboutForm();
            about.ShowDialog();
        }

        #endregion

        #region Context Tool Strip Menu Events

        private void toolStripMenuItemDisable_Click(object sender, EventArgs e)
        {
            DisableItem(currentIndex);
        }

        private void toolStripMenuItemEnable_Click(object sender, EventArgs e)
        {
            EnableItem(currentIndex);
        }

        private void toolStripMenuItemDelete_Click(object sender, EventArgs e)
        {

            // Display a warning message before deleting an item.
            DialogResult result = MessageBox.Show(
                "Warning: Do not delete startup items unless you are 100%" + "\r\n" +
                "sure of what you are doing. In most cases, it is recommended" + "\r\n" +
                "that you use the "Disable" option instead." + "\r\n" + "\r\n" +
                "Do you still want to delete the selected item?", Application.ProductName,
                MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

            if (result == DialogResult.No)
            {
                return;
            }
            else
            {
                DeleteItem(currentIndex);
            }
        }

        private void toolStripMenuItemOpen_Click(object sender, EventArgs e)
        {
            OpenFolder(currentIndex);
        }

        private void toolStripMenuItemExecute_Click(object sender, EventArgs e)
        {
            ExecuteCommand(currentIndex);
        }

        private void toolStripMenuItemMoveToCurrentUser_Click(object sender, EventArgs e)
        {
            MoveToCurrentUser(currentIndex);
        }

        private void toolStripMenuItemMoveToAllUsers_Click(object sender, EventArgs e)
        {
            MoveToAllUsers(currentIndex);
        }

        #endregion

        #region Tool Strip Button Events

        private void toolStripButtonDisable_Click(object sender, EventArgs e)
        {
            DisableItem(currentIndex);
        }

        private void toolStripButtonEnable_Click(object sender, EventArgs e)
        {
            EnableItem(currentIndex);
        }

        private void toolStripButtonDelete_Click(object sender, EventArgs e)
        {

            // Display a warning message before deleting an item.
            DialogResult result = MessageBox.Show(
                "Warning: Do not delete startup items unless you are 100%" + "\r\n" +
                "sure of what you are doing. In most cases, it is recommended" + "\r\n" +
                "that you use the "Disable" option instead." + "\r\n" + "\r\n" +
                "Do you still want to delete the selected item?", Application.ProductName,
                MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

            if (result == DialogResult.No)
            {
                return;
            }
            else
            {
                DeleteItem(currentIndex);
            }

        }

        private void toolStripButtonOpen_Click(object sender, EventArgs e)
        {
            OpenFolder(currentIndex);
        }

        private void toolStripButtonExecute_Click(object sender, EventArgs e)
        {
            ExecuteCommand(currentIndex);
        }

        private void toolStripButtonMoveToCurrentUser_Click(object sender, EventArgs e)
        {
            MoveToCurrentUser(currentIndex);
        }

        private void toolStripButtonMoveToAllUsers_Click(object sender, EventArgs e)
        {
            MoveToAllUsers(currentIndex);
        }

        private void toolStripButtonRefresh_Click(object sender, EventArgs e)
        {
            FillListview();
        }

        #endregion

        #region Listview Methods

        private void FillListview()
        {
            // Clear image list and listview.
            listviewStartup.Items.Clear();
            imageListStartupManager.Images.Clear();
            i = 0;

            // Get all startup programs in HHEY_CURRENT_USER
            DisplayRegistryStartupEntries(HKCU);

            // Get all startup programs in HKEY_LOCAL_MACHINE
            DisplayRegistryStartupEntries(HKLM);

            // Get all startup shortcuts and programs in the Current User's Startup Folder.
            DisplayStartupShortcuts(StartupCurrentUser);

            // Get all startup shortcuts and programs in the All User's Startup Folder.
            DisplayStartupShortcuts(StartupAllUsers);
        }
       
        private void SetItems(int index, string context)
        {
            // Set state of "Enable" and "Disable" menus according to enabled state of selected item.
            if (listviewStartup.Items[index].SubItems[(int)ListCol.Status].Text.Contains("Enabled"))
            {
                toolStripMenuItemEnable.Enabled = false;
                toolStripButtonEnable.Enabled = false;
                toolStripMenuItemDisable.Enabled = true;
                toolStripButtonDisable.Enabled = true;
                toolStripMenuItemDelete.Enabled = true;     // Only allow enabled items to be deleted.
                toolStripButtonDelete.Enabled = true;
                toolStripMenuItemExecute.Enabled = true;    // Only allow enabled items to be executed.
                toolStripButtonExecute.Enabled = true;
                toolStripMenuItemOpen.Enabled = true;       // Only allow enabled items to have folder opened.
                toolStripButtonOpen.Enabled = true;
               
                // Disable items based on context.
                if (context == "Current User")
                {
                    toolStripMenuItemMoveToAllUsers.Enabled = true;
                    toolStripButtonMoveToAllUsers.Enabled = true;
                    toolStripMenuItemMoveToCurrentUser.Enabled = false; // Item is already in Current User.
                    toolStripButtonMoveToCurrentUser.Enabled = false;
                }
                else if (context == "All Users")
                {
                    toolStripMenuItemMoveToAllUsers.Enabled = false;     // Itme is already in All Users.
                    toolStripButtonMoveToAllUsers.Enabled = false;
                    toolStripMenuItemMoveToCurrentUser.Enabled = true;
                    toolStripButtonMoveToCurrentUser.Enabled = true;
                }
            }
            else
            {
                toolStripMenuItemEnable.Enabled = true;
                toolStripButtonEnable.Enabled = true;
                toolStripMenuItemDisable.Enabled = false;
                toolStripButtonDisable.Enabled = false;
                toolStripMenuItemDelete.Enabled = false;    // Do not allow disabled items to be deleted.
                toolStripButtonDelete.Enabled = false;
                toolStripMenuItemExecute.Enabled = false;   // Do not allow disabled items to be executed.
                toolStripButtonExecute.Enabled = false;
                toolStripMenuItemOpen.Enabled = false;      // Do not allow disabled items to have folder opened.
                toolStripButtonOpen.Enabled = false;
                toolStripMenuItemMoveToAllUsers.Enabled = false;    // Do not allow disabled item to be moved.
                toolStripButtonMoveToAllUsers.Enabled = false;
                toolStripMenuItemMoveToCurrentUser.Enabled = false; // Item is already in Current User.
                toolStripButtonMoveToCurrentUser.Enabled = false;
            }
        }

        #endregion

        #region Display Registry Startup Entries Method

        private void DisplayRegistryStartupEntries(string hive)
        {
            bool disabled;
            string command;
            string filePath;
            RegistryKey rk;

            if (hive == HKCU)
            {
                // Get all startup programs in HKEY_CURRENT_USER.
                rk = Registry.CurrentUser.OpenSubKey(runKey);
            }
            else
            {
                // Get all startup programs in HKEY_LOCAL_MACHINE.
                rk = Registry.LocalMachine.OpenSubKey(runKey);
            }

            // Get all of the entries.
            foreach (string value in rk.GetValueNames())
            {
                // Reset disabled flag.
                disabled = false;

                // Save complete command.
                command = rk.GetValue(value).ToString();

                // Check if command is disabled (begins with a ":")
                if (command.StartsWith(":"))
                {
                    // Flag this entry as disabled.
                    disabled = true;

                    // Remove semicolon so that path command works and save file path.
                    filePath = ReturnFilePath(command.Remove(0, 1));
                }
                else
                {
                    // Save file path.
                    filePath = ReturnFilePath(command);
                }

                // Attempt to get application image (icon).
                if (native.GetIcon(filePath) != null)
                {
                    // Add the icon to the image list so that the listview can access it.
                    imageListStartupManager.Images.Add(native.GetIcon(filePath));

                }
                else
                {
                    // If there is no icon, just add a blank image from resources to keep the indexes proper.
                    imageListStartupManager.Images.Add((System.Drawing.Image)ResourceManager.GetObject("Blank"));
                }

                // Add entry description to listview.
                listviewStartup.Items.Add(value.ToString(), i);

                // Add file name (without path) to listview.
                listviewStartup.Items[i].SubItems.Add(Path.GetFileName(filePath));

                // Add location (type) information to listview.
                if (hive == HKCU)
                {
                    listviewStartup.Items[i].SubItems.Add(HKCU);
                }
                else
                {
                    listviewStartup.Items[i].SubItems.Add(HKLM);
                }

                // Add status information.
                if (disabled)
                {
                    listviewStartup.Items[i].SubItems.Add("Disabled");
                }
                else
                {
                    listviewStartup.Items[i].SubItems.Add("Enabled");
                }

                // Add command.
                listviewStartup.Items[i].SubItems.Add(command);

                // Add file path.
                listviewStartup.Items[i].SubItems.Add(filePath);

                i++;
            }

            // Close the registry key.
            rk.Close();
        }

        #endregion

        #region Display Startup Shortcuts Method

        private void DisplayStartupShortcuts(string type)
        {
            bool disabled;
            string command;
            string filePath;
            string folder;

            if (type == StartupCurrentUser)
            {
                // Current users startup folder.
                folder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            }
            else
            {
                // All users startup folder.
                folder = Environment.ExpandEnvironmentVariables("%AllUsersProfile%")
                    + @"\Start Menu\Programs\Startup";
            }

            foreach (string shortcut in Directory.GetFiles(folder, "*.*"))
            {
                // Only process shortcuts, executibles, or disabled shortcuts.
                if (Path.GetExtension(shortcut) == ".lnk" || Path.GetExtension(shortcut) == ".exe"
                    || Path.GetExtension(shortcut) == ".disabled")
                {
                    // Set diabled flag.
                    if (Path.GetExtension(shortcut) == ".disabled")
                    {
                        disabled = true;
                    }
                    else
                    {
                        disabled = false;
                    }

                    // Save complete command.
                    command = shortcut;

                    // Save file path.
                    filePath = ReturnFilePath(command);

                    // Resolve the shortcut.
                    ShortcutClass sc = new ShortcutClass(filePath);

                    // Attempt to get application image (icon).
                    if (sc.Icon != null)
                    {
                        // First try getting icon from shortcut.
                        imageListStartupManager.Images.Add(sc.Icon);
                    }
                    else if (native.GetIcon(sc.Path) != null)
                    {
                        // Then try getting icon from the resolved path.
                        imageListStartupManager.Images.Add(native.GetIcon(sc.Path));
                    }
                    else
                    {
                        // If both methods fail, display a blank icon.
                        imageListStartupManager.Images.Add((System.Drawing.Image)ResourceManager.GetObject("Blank"));
                    }

                    // Add entry description to listview.
                    listviewStartup.Items.Add(Path.GetFileNameWithoutExtension(shortcut), i);

                    // Add file name (without path) to listview.
                    listviewStartup.Items[i].SubItems.Add(Path.GetFileName(filePath));

                    // Add type information to listview.
                    if (type == StartupCurrentUser)
                    {
                        listviewStartup.Items[i].SubItems.Add(StartupCurrentUser);
                    }
                    else
                    {
                        listviewStartup.Items[i].SubItems.Add(StartupAllUsers);
                    }

                    // Add status information.
                    if (disabled)
                    {
                        listviewStartup.Items[i].SubItems.Add("Disabled");
                    }
                    else
                    {
                        listviewStartup.Items[i].SubItems.Add("Enabled");
                    }

                    // Add command.
                    listviewStartup.Items[i].SubItems.Add(command);

                    // Add file path.
                    listviewStartup.Items[i].SubItems.Add(filePath);

                    i++;

                }

            }

        }

        #endregion

        #region Return FilePath Method

        private static string ReturnFilePath(string value)
        {
            try
            {
                int p;

                // Check for quotes, and if present, remove them.
                if (value.Contains("""))   // quote character 34, 22H
                {
                    value = value.Replace(""", "");
                }

                // Check for hyphens, and if present, return the part before first one.
                if (value.Contains("-"))
                {
                    p = value.IndexOf("-");
                    value = value.Substring(0, p - 1);
                }

                // Check for forward slashes, and if present, return the part before first one.
                if (value.Contains("/"))
                {
                    p = value.IndexOf("/");
                    value = value.Substring(0, p - 1);
                }

                // Check for a space followed by a percent sign, and if present, return the part before the first one.
                if (value.Contains(" %"))
                {
                    p = value.IndexOf(" %");
                    value = value.Substring(0, p);
                }

                if (!string.IsNullOrEmpty(value))
                {
                    return Path.GetFullPath(value);
                }
                else
                {
                    return "";
                }
            }
            catch (DirectoryNotFoundException e)
            {
                MessageBox.Show("The folder was not found." + "\r\n" +
                    "Description: " + e.Message + "\r\n" + "Command: " + value,
                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "";
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show("The file was not found." + "\r\n" +
                    "Description: " + ex.Message + "\r\n" + "Command: " + value,
                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "";
            }

        }

        #endregion

        #region Enable Item Method

        private void EnableItem(int index)
        {
            RegistryKey rk = null;
            string filePath = "";
            string newFilePath = "";

            try
            {
                string command;

                // Get type (location) of startup item.
                switch (listviewStartup.Items[index].SubItems[(int)ListCol.Type].Text)
                {
                    case HKCU:

                        // Open "Run" key in HKEY_CURRENT_USER and get value for this entry.
                        rk = Registry.CurrentUser.OpenSubKey(runKey, true);
                        command = rk.GetValue(listviewStartup.Items[index].Text).ToString();

                        // Check that entry begins with a colon (:), which indicates it is disabled.
                        if (command.StartsWith(":"))
                        {
                            // Remove the leading colon.
                            command = command.Remove(0, 1);
                           
                            // Replace the command in the registry without the colon.
                            rk.SetValue(listviewStartup.Items[index].Text, command);

                            // Change the listview to indicate that this item is now enabled.
                            listviewStartup.Items[index].SubItems[(int)ListCol.Status].Text = "Enabled";
                       
                            // Set context menu and tool strip buttons.
                            SetItems(index, "Current User");
                        }

                        break;

                    case HKLM:

                        // Open "Run" key in HKEY_LOCAL_MACHINE and get value for this entry.
                        rk = Registry.LocalMachine.OpenSubKey(runKey, true);
                        command = rk.GetValue(listviewStartup.Items[index].Text).ToString();

                        // Check that entry begins with a colon (:), which indicates it is disabled.
                        if (command.StartsWith(":"))
                        {
                            // Remove the leading colon.
                            command = command.Remove(0, 1);

                            // Replace the command in the registry without the colon.
                            rk.SetValue(listviewStartup.Items[index].Text, command);

                            // Change the listview to indicate that this item is now enabled.
                            listviewStartup.Items[index].SubItems[(int)ListCol.Status].Text = "Enabled";

                            // Set context menu and tool strip buttons.
                            SetItems(index, "All Users");
                        }

                        break;

                    case StartupCurrentUser:

                        // Get the path.
                        filePath = listviewStartup.Items[index].SubItems[(int)ListCol.Path].Text;

                        // Make sure the shortcut exists.
                        if (File.Exists(filePath))
                        {
                            // Remove any attributes.
                            File.SetAttributes(filePath, FileAttributes.Normal);

                            // Make sure this is a .disabled file.
                            if (Path.GetExtension(filePath) == ".disabled")
                            {
                                // Rename the file with a ".lnk" extension.
                                newFilePath = Path.GetFullPath(filePath).Replace(Path.GetExtension(filePath), "") + ".lnk";
                                File.Move(filePath, newFilePath);

                                // Change the listview to indicate that this item is now enabled.
                                listviewStartup.Items[index].SubItems[(int)ListCol.Status].Text = "Enabled";

                                // Store the new path in the listview.
                                listviewStartup.Items[index].SubItems[(int)ListCol.Path].Text = newFilePath;

                                // Store the new filename in the listview.
                                listviewStartup.Items[index].SubItems[(int)ListCol.FileName].Text = Path.GetFileName(newFilePath);
                               
                                // Set context menu and tool strip buttons.
                                SetItems(index, "Current User");
                            }
                            else
                            {
                                MessageBox.Show("The file does not appear to be a valid shortcut.",
                                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            }
                        }
                        else
                        {
                            //  Cannot find file.
                            MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                       
                        break;
                    case StartupAllUsers:

                        // Get the path.
                        filePath = listviewStartup.Items[index].SubItems[(int)ListCol.Path].Text;

                        // Make sure the shortcut exists.
                        if (File.Exists(filePath))
                        {
                            // Remove any attributes.
                            File.SetAttributes(filePath, FileAttributes.Normal);

                            // Make sure this is a .disabled file.
                            if (Path.GetExtension(filePath) == ".disabled")
                            {
                                // Rename the file with a ".lnk" extension.
                                newFilePath = Path.GetFullPath(filePath).Replace(Path.GetExtension(filePath), "") + ".lnk";
                                File.Move(filePath, newFilePath);

                                // Change the listview to indicate that this item is now enabled.
                                listviewStartup.Items[index].SubItems[(int)ListCol.Status].Text = "Enabled";

                                // Store the new path in the listview.
                                listviewStartup.Items[index].SubItems[(int)ListCol.Path].Text = newFilePath;

                                // Store the new filename in the listview.
                                listviewStartup.Items[index].SubItems[(int)ListCol.FileName].Text = Path.GetFileName(newFilePath);

                                // Set context menu and tool strip buttons.
                                SetItems(index, "All Users");
                            }
                            else
                            {
                                MessageBox.Show("The file does not appear to be a valid shortcut.",
                                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            }
                        }
                        else
                        {
                            //  Cannot find file.
                            MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                       
                        break;
                    default:
                        // Do nothing.
                        break;
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show("Unable to enable this item." + "\r\n" +
                    "The system returned the following information:" + "\r\n" +
                    ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (ArgumentException exc)
            {
                MessageBox.Show("Unable to enable this item." + "\r\n" +
                    "The system returned the following information:" + "\r\n" +
                    exc.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (SecurityException excep)
            {
                MessageBox.Show("Unable to enable this item." + "\r\n" +
                    "The system returned the following information:" + "\r\n" +
                    excep.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Win32Exception)
            {
                //  Cannot find file.
                MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                // Close registry key.
                if (rk != null)
                {
                    rk.Close();
                }
            }
        }

        #endregion

        #region Disable Item Method

        private void DisableItem(int index)
        {
            RegistryKey rk = null;
            string filePath = "";
            string newFilePath = "";

            try
            {
                string command;

                // Get type (location) of startup item.
                switch (listviewStartup.Items[index].SubItems[(int)ListCol.Type].Text)
                {
                    case HKCU:

                        // Open "Run" key in HKEY_CURRENT_USER and get value for this entry.
                        rk = Registry.CurrentUser.OpenSubKey(runKey, true);
                        command = rk.GetValue(listviewStartup.Items[index].Text).ToString();

                        // Check that entry does not begins with a colon (:), which would indicate it is already disabled.
                        if (!command.StartsWith(":"))
                        {
                            // Add the leading colon.
                            command = ":" + command;

                            // Replace the command in the registry without the colon.
                            rk.SetValue(listviewStartup.Items[index].Text, command);

                            // Change the listview to indicate that this item is now disabled.
                            listviewStartup.Items[index].SubItems[(int)ListCol.Status].Text = "Disabled";

                            // Set context menu and tool strip buttons.
                            SetItems(index, "Current User");
                        }

                        break;

                    case HKLM:

                        // Open "Run" key in HKEY_LOCAL_MACHINE and get value for this entry.
                        rk = Registry.LocalMachine.OpenSubKey(runKey, true);
                        command = rk.GetValue(listviewStartup.Items[index].Text).ToString();

                        // Check that entry does not begins with a colon (:), which would indicate it is already disabled.
                        if (!command.StartsWith(":"))
                        {
                            // Add the leading colon.
                            command = ":" + command;

                            // Replace the command in the registry without the colon.
                            rk.SetValue(listviewStartup.Items[index].Text, command);

                            // Change the listview to indicate that this item is now disabled.
                            listviewStartup.Items[index].SubItems[(int)ListCol.Status].Text = "Disabled";

                            // Set context menu and tool strip buttons.
                            SetItems(index, "All Users");
                        }

                        break;

                    case StartupCurrentUser:
                       
                        // Get the path.
                        filePath = listviewStartup.Items[index].SubItems[(int)ListCol.Path].Text;

                        // Make sure the shortcut exists.
                        if (File.Exists(filePath))
                        {
                            // Remove any attributes.
                            File.SetAttributes(filePath, FileAttributes.Normal);

                            // Make sure this is a .lnk file.
                            if (Path.GetExtension(filePath) == ".lnk")
                            {
                                // Rename the file with a ".disabled" extension.
                                newFilePath = Path.GetFullPath(filePath).Replace(Path.GetExtension(filePath), "") + ".disabled";
                                File.Move(filePath, newFilePath);

                                // Change the listview to indicate that this item is now disabled.
                                listviewStartup.Items[index].SubItems[(int)ListCol.Status].Text = "Disabled";

                                // Store the new path in the listview.
                                listviewStartup.Items[index].SubItems[(int)ListCol.Path].Text = newFilePath;

                                // Store the new filename in the listview.
                                listviewStartup.Items[index].SubItems[(int)ListCol.FileName].Text = Path.GetFileName(newFilePath);

                                // Set context menu and tool strip buttons.
                                SetItems(index, "Current User");
                            }
                            else
                            {
                                MessageBox.Show("The file does not appear to be a valid shortcut.",
                                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            }
                        }
                        else
                        {
                            //  Cannot find file.
                            MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                       
                        break;
                   
                    case StartupAllUsers:
                       
                        // Get the path.
                        filePath = listviewStartup.Items[index].SubItems[(int)ListCol.Path].Text;

                        // Make sure the shortcut exists.
                        if (File.Exists(filePath))
                        {
                            // Remove any attributes.
                            File.SetAttributes(filePath, FileAttributes.Normal);

                            // Make sure this is a .lnk file.
                            if (Path.GetExtension(filePath) == ".lnk")
                            {
                                // Rename the file with a ".disabled" extension.
                                newFilePath = Path.GetFullPath(filePath).Replace(Path.GetExtension(filePath), "") + ".disabled";
                                File.Move(filePath, newFilePath);

                                // Change the listview to indicate that this item is now disabled.
                                listviewStartup.Items[index].SubItems[(int)ListCol.Status].Text = "Disabled";

                                // Store the new path in the listview.
                                listviewStartup.Items[index].SubItems[(int)ListCol.Path].Text = newFilePath;

                                // Store the new filename in the listview.
                                listviewStartup.Items[index].SubItems[(int)ListCol.FileName].Text = Path.GetFileName(newFilePath);

                                // Set context menu and tool strip buttons.
                                SetItems(index, "All Users");
                            }
                            else
                            {
                                MessageBox.Show("The file does not appear to be a valid shortcut.",
                                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            }
                        }
                        else
                        {
                            //  Cannot find file.
                            MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                       
                        break;
                    default:
                        // Do nothing.
                        break;
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show("Unable to disable this item." + "\r\n" +
                    "The system returned the following information:" + "\r\n" +
                    ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (ArgumentException exc)
            {
                MessageBox.Show("Unable to disable this item." + "\r\n" +
                    "The system returned the following information:" + "\r\n" +
                    exc.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (SecurityException excep)
            {
                MessageBox.Show("Unable to disable this item." + "\r\n" +
                    "The system returned the following information:" + "\r\n" +
                    excep.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Win32Exception)
            {
                //  Cannot find file.
                MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                // Close registry key.
                if (rk != null)
                {
                    rk.Close();
                }
            }
        }

        #endregion

        #region Delete Item Method

        private void DeleteItem(int index)
        {
            RegistryKey rk = null;
            string fileName;

            try
            {

                // Get type (location) of startup item.
                switch (listviewStartup.Items[index].SubItems[(int)ListCol.Type].Text)
                {
                    case HKCU:

                        // Open "Run" key in HKEY_CURRENT_USER.
                        rk = Registry.CurrentUser.OpenSubKey(runKey, true);

                        // Attempt to delete the value.
                        rk.DeleteValue(listviewStartup.Items[index].Text);

                        // Remove item from listview.
                        listviewStartup.Items[index].Remove();

                        // Clear the details labels.
                        labelArguments.Text = "";
                        labelCommand.Text = "";
                        labelCompany.Text = "";
                        labelDescription.Text = "";
                        labelFileVersion.Text = "";
                        labelProductName.Text = "";

                        break;

                    case HKLM:

                        // Open "Run" key in HKEY_LOCAL_MACHINE.
                        rk = Registry.LocalMachine.OpenSubKey(runKey, true);

                        // Attempt to delete the value.
                        rk.DeleteValue(listviewStartup.Items[index].Text);

                        // Remove item from listview.
                        listviewStartup.Items[index].Remove();

                        // Clear the details labels.
                        labelArguments.Text = "";
                        labelCommand.Text = "";
                        labelCompany.Text = "";
                        labelDescription.Text = "";
                        labelFileVersion.Text = "";
                        labelProductName.Text = "";

                        break;

                    case StartupCurrentUser:

                        // Get the file name.
                        fileName = listviewStartup.Items[index].SubItems[(int)ListCol.Path].Text;

                        // Make sure file exists.
                        if (File.Exists(fileName))
                        {
                            // Remove attributes.
                            File.SetAttributes(fileName, FileAttributes.Normal);

                            // Delete file.
                            File.Delete(fileName);

                            // Remove item from listview.
                            listviewStartup.Items[index].Remove();

                            // Clear the details labels.
                            labelArguments.Text = "";
                            labelCommand.Text = "";
                            labelCompany.Text = "";
                            labelDescription.Text = "";
                            labelFileVersion.Text = "";
                            labelProductName.Text = "";
                        }
                        else
                        {
                            MessageBox.Show("The file was not found.", Application.ProductName,
                                MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        }
                       
                        break;

                    case StartupAllUsers:

                        // Get the file name.
                        fileName = listviewStartup.Items[index].SubItems[(int)ListCol.Path].Text;

                        // Make sure file exists.
                        if (File.Exists(fileName))
                        {
                            // Remove attributes.
                            File.SetAttributes(fileName, FileAttributes.Normal);

                            // Delete file.
                            File.Delete(fileName);

                            // Remove item from listview.
                            listviewStartup.Items[index].Remove();

                            // Clear the details labels.
                            labelArguments.Text = "";
                            labelCommand.Text = "";
                            labelCompany.Text = "";
                            labelDescription.Text = "";
                            labelFileVersion.Text = "";
                            labelProductName.Text = "";
                        }
                        else
                        {
                            MessageBox.Show("The file was not found.", Application.ProductName,
                                MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        }

                        break;
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show("Unable to delete this item." + "\r\n" +
                    "The system returned the following information:" + "\r\n" +
                    ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (ArgumentException exc)
            {
                MessageBox.Show("Unable to delete this item." + "\r\n" +
                    "The system returned the following information:" + "\r\n" +
                    exc.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (SecurityException excep)
            {
                MessageBox.Show("Unable to delete this item." + "\r\n" +
                    "The system returned the following information:" + "\r\n" +
                    excep.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Win32Exception except)
            {
                MessageBox.Show("Unable to delete this item." + "\r\n" +
                    "The system returned the following information:" + "\r\n" +
                    except.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // Close registry key.
                if (rk != null)
                {
                    rk.Close();
                }
            }
        }

        #endregion

        #region Open Folder Method

        private void OpenFolder(int index)
        {
            try
            {
                string folder;

                // Get path of the startup item.
                folder = listviewStartup.Items[index].SubItems[(int)ListCol.Path].Text;

                // If path exists, open the folder with Explorer.
                if (File.Exists(folder))
                {
                    // Get just the directory.
                    folder = Path.GetDirectoryName(folder);

                    // Start Explorer.
                    ProcessStartInfo startInfo =
                        new ProcessStartInfo(Environment.GetEnvironmentVariable("windir") + "\\explorer.exe");
                    startInfo.Arguments = " /root, " + folder;
                    startInfo.WindowStyle = ProcessWindowStyle.Normal;
                    Process.Start(startInfo);
                }
                else
                {
                //  Cannot find file.
                MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show("Unable to open the folder containing this item."
                    + "\r\n" + "The system returned the following information:" + "\r\n" +
                    ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (ArgumentException exc)
            {
                MessageBox.Show("Unable to open the folder containing this item."
                    + "\r\n" + "The system returned the following information:" + "\r\n" +
                    exc.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (SecurityException excep)
            {
                MessageBox.Show("Unable to open the folder containing this item."
                    + "\r\n" + "The system returned the following information:" + "\r\n" +
                    excep.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Win32Exception)
            {
                //  Cannot find file.
                MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        #endregion

        #region Execute Command Method

        private void ExecuteCommand(int index)
        {
            try
            {
                string fileName;
                string arguments;

                // Get the file name with path.
                fileName = listviewStartup.Items[index].SubItems[(int)ListCol.Path].Text;
               
                // If the file is a shortcut, resolve it; otherwise use filename.
                if (Path.GetExtension(fileName) == ".lnk")
                {
                    ShortcutClass sc = new ShortcutClass(fileName);
                    fileName = sc.Path;
                    arguments = sc.Arguments;

                    sc.Dispose();
                }
                else
                {
                    // Get the complete command.
                    string command = listviewStartup.Items[index].SubItems[(int)ListCol.Command].Text;
                   
                    // Get the arguments by removing the folder and filename (path).
                    arguments = command.Replace(fileName, "");

                    // Remove and quotes.
                    arguments = arguments.Replace(""", "");
                }
               
                if (File.Exists(fileName))
                {
                    // Start Explorer.
                    ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
                    startInfo.Arguments = arguments;
                    startInfo.WindowStyle = ProcessWindowStyle.Normal;
                    Process.Start(startInfo);
                }
                else
                {
                    //  Cannot find file.
                    MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show("Unable to execute this item."
                    + "\r\n" + "The system returned the following information:" + "\r\n" +
                    ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (ArgumentException exc)
            {
                MessageBox.Show("Unable to execute this item."
                    + "\r\n" + "The system returned the following information:" + "\r\n" +
                    exc.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (SecurityException excep)
            {
                MessageBox.Show("Unable to execute this item."
                    + "\r\n" + "The system returned the following information:" + "\r\n" +
                    excep.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Win32Exception)
            {
                    MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        #endregion

        #region Move to All Users Method

        private void MoveToAllUsers(int index)
        {
            RegistryKey rk = null;

            try
            {
                string name;
                string command;
                string filePath;
                string newFilePath;

                // Get type (location) of startup item.
                switch (listviewStartup.Items[index].SubItems[(int)ListCol.Type].Text)
                {
                    case HKCU:

                        // Open "Run" key in HKEY_CURRENT_USER and get value.
                        rk = Registry.CurrentUser.OpenSubKey(runKey, true);
                        name = listviewStartup.Items[index].Text;
                        command = rk.GetValue(name).ToString();

                        // Delete the value in HKEY_LOCAL_MACHINE.
                        rk.DeleteValue(name);

                        rk.Close();

                        // Open "Run" key in HKEY_LOCAL_MACHINE and set the value.
                        rk = Registry.LocalMachine.OpenSubKey(runKey, true);
                        rk.SetValue(name, command);

                        rk.Close();

                        // Change the listview to indicate that this item is now disabled.
                        listviewStartup.Items[index].SubItems[(int)ListCol.Type].Text = HKLM;

                        // Set context menu and tool strip buttons.
                        SetItems(index, "All Users");

                        break;

                    case HKLM:
                        // Do nothing. Startup item is already in All Users.
                        break;
                    case StartupCurrentUser:
                       
                        // Get the file name.
                        name = listviewStartup.Items[index].SubItems[(int)ListCol.FileName].Text;

                        // Get the current path.
                        filePath = currentUserStartup + name;
                       
                        // Get the new path.
                        newFilePath = allUsersStartup + name;

                        if (File.Exists(filePath))
                        {
                            // Remove any attributes.
                            File.SetAttributes(filePath, FileAttributes.Normal);

                            // Move the shortcut from Current User to All Users.
                            File.Move(filePath, newFilePath);
                       
                            // Change the location in the listview.
                            listviewStartup.Items[index].SubItems[(int)ListCol.Type].Text = StartupAllUsers;

                            // Set context menu and tool strip buttons.
                            SetItems(index, "All Users");
                        }
                        else
                        {
                            MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }

                        break;

                    case StartupAllUsers:
                        // Do nothing. Startup item is already in All Users.
                        break;
                    default:
                        // Do nothing.
                        break;
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show("Unable to move this item."
                    + "\r\n" + "The system returned the following information:" + "\r\n" +
                    ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (ArgumentException exc)
            {
                MessageBox.Show("Unable to move this item."
                    + "\r\n" + "The system returned the following information:" + "\r\n" +
                    exc.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (SecurityException excep)
            {
                MessageBox.Show("Unable to move this item."
                    + "\r\n" + "The system returned the following information:" + "\r\n" +
                    excep.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Win32Exception)
            {
                MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                // Close registry key.
                if (rk != null)
                {
                    rk.Close();
                }
            }
        }

        #endregion

        #region Move to Current User Method

        private void MoveToCurrentUser(int index)
        {
            RegistryKey rk = null;

            try
            {
                string name;
                string command;
                string filePath;
                string newFilePath;
               
                // Get type (location) of startup item.
                switch (listviewStartup.Items[index].SubItems[(int)ListCol.Type].Text)
                {
                    case HKCU:
                        // Do nothing. Startup item is already in Current User.
                        break;
                    case HKLM:
                      
                        // Open "Run" key in HKEY_LOCAL_MACHINE and get value.
                        rk = Registry.LocalMachine.OpenSubKey(runKey, true);
                        name = listviewStartup.Items[index].Text;
                        command = rk.GetValue(name).ToString();

                        // Delete the value in HKEY_LOCAL_MACHINE.
                        rk.DeleteValue(name);

                        rk.Close();

                        // Open "Run" key in HKEY_CURRENT_USER and set the value.
                        rk = Registry.CurrentUser.OpenSubKey(runKey, true);
                        rk.SetValue(name, command);
                       
                        rk.Close();

                        // Change the listview to indicate that this item is now disabled.
                        listviewStartup.Items[index].SubItems[(int)ListCol.Type].Text = HKCU;

                        // Set context menu and tool strip buttons.
                        SetItems(index, "Current User");

                        break;
                    case StartupCurrentUser:
                        // Do nothing. Startup item is already in Current User.
                        break;
                    case StartupAllUsers:

                        // Get the file name.
                        name = listviewStartup.Items[index].SubItems[(int)ListCol.FileName].Text;

                        // Get the current path.
                        filePath = allUsersStartup + name;

                        // Get the new path.
                        newFilePath = currentUserStartup + name;

                        if (File.Exists(filePath))
                        {
                            // Remove any attributes.
                            File.SetAttributes(filePath, FileAttributes.Normal);

                            // Move the shortcut from All Users to Current User.
                            File.Move(filePath, newFilePath);

                            // Change the listview to indicate that this item is now disabled.
                            listviewStartup.Items[index].SubItems[(int)ListCol.Type].Text = StartupCurrentUser;

                            // Set context menu and tool strip buttons.
                            SetItems(index, "Current User");
                        }
                        else
                        {
                            MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }

                        break;

                    default:
                        // Do nothing.
                        break;
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show("Unable to move this item."
                    + "\r\n" + "The system returned the following information:" + "\r\n" +
                    ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (ArgumentException exc)
            {
                MessageBox.Show("Unable to move this item."
                    + "\r\n" + "The system returned the following information:" + "\r\n" +
                    exc.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (SecurityException excep)
            {
                MessageBox.Show("Unable to move this item."
                    + "\r\n" + "The system returned the following information:" + "\r\n" +
                    excep.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Win32Exception)
            {
                MessageBox.Show("The file and/or folder cannot be found.", Application.ProductName,
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                // Close registry key.
                if (rk != null)
                {
                    rk.Close();
                }
            }
        }

        #endregion

    }
}

Project Homepage: