Как запустить приложение C# при запуске Windows?

Я сделал приложение, которое запускается во время запуска, со следующим кодом ниже.
Процесс запускается на инструменте диспетчера процессов после перезапуска, но я не вижу приложение на экране. Когда я открываю тот же файл.exe из значения реестра запуска, программа работает идеально.

// The path to the key where Windows looks for startup applications
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

// Add the value in the registry so that the application runs at startup
rkApp.SetValue("MyApp", Application.ExecutablePath.ToString());

Что я могу сделать, чтобы исправить это?

12 ответов

Код здесь (выигрышная форма приложения):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace RunAtStartup
{
    public partial class frmStartup : Form
    {
        // The path to the key where Windows looks for startup applications
        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        public frmStartup()
        {
            InitializeComponent();
            // Check to see the current state (running at startup or not)
            if (rkApp.GetValue("MyApp") == null)
            {
                // The value doesn't exist, the application is not set to run at startup
                chkRun.Checked = false;
            }
            else
            {
                // The value exists, the application is set to run at startup
                chkRun.Checked = true;
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (chkRun.Checked)
            {
                // Add the value in the registry so that the application runs at startup
                rkApp.SetValue("MyApp", Application.ExecutablePath);
            }
            else
            {
                // Remove the value from the registry so that the application doesn't start
                rkApp.DeleteValue("MyApp", false);
            }
        }
    }
}

Попробуйте этот код

private void RegisterInStartup(bool isChecked)
{
    RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    if (isChecked)
    {
        registryKey.SetValue("ApplicationName", Application.ExecutablePath);
    }
    else
    {
        registryKey.DeleteValue("ApplicationName");
    }
}

Источник: http: //www.dotnet сбоку.ру / 09/ 26/ run- the-application- at- windows- startup/

Вы можете попробовать скопировать ярлык для вашего приложения в папку автозагрузки вместо того, чтобы что-то добавлять в реестр. Вы можете получить путь с Environment.SpecialFolder.Startup, Это доступно во всех платформах.net начиная с версии 1.1.

В качестве альтернативы, возможно, этот сайт будет вам полезен, в нем перечислено множество различных способов автоматического запуска приложения.

public class StartUpManager
{
    public static void AddApplicationToCurrentUserStartup()
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.SetValue("My ApplicationStartUpDemo", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
        }
    }

    public static void AddApplicationToAllUserStartup()
    {
        using (RegistryKey key =     Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.SetValue("My ApplicationStartUpDemo", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
        }
    }

    public static void RemoveApplicationFromCurrentUserStartup()
    {
         using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
         {
             key.DeleteValue("My ApplicationStartUpDemo", false);
         }
    }

    public static void RemoveApplicationFromAllUserStartup()
    {
        using (RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.DeleteValue("My ApplicationStartUpDemo", false);
        }
    }

    public static bool IsUserAdministrator()
    {
        //bool value to hold our return value
        bool isAdmin;
        try
        {
            //get the currently logged in user
            WindowsIdentity user = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(user);
            isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        catch (UnauthorizedAccessException ex)
        {
            isAdmin = false;
        }
        catch (Exception ex)
        {
            isAdmin = false;
        }
        return isAdmin;
    }
}

Вы можете проверить всю статью здесь

1- добавить пространство имен:

using Microsoft.Win32;

2-добавить приложение для регистрации:

RegistryKey key=Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("your_app_name", Application.ExecutablePath);

3 - если вы хотите удалить приложение из реестра:

key.DeleteValue("your_app_name",false);

Сначала я попробовал код ниже, и он не работал

RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("MyAPP", Application.ExecutablePath.ToString());

Затем я изменил CurrentUser с LocalMachine, и он работает

RegistryKey rkApp = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("MyAPP", Application.ExecutablePath.ToString());

Я не нашел ни одного из приведенного выше кода работает. Может быть, это потому, что мое приложение работает на.NET 3.5. Я не знаю. Следующий код работал отлично для меня. Я получил это от старшего разработчика приложений.NET в моей команде.

Write (Microsoft.Win32.Registry.LocalMachine, @ "ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ \Microsoft\Windows\CurrentVersion\Run\", "WordWatcher", "\"" + Application.ExecutablePath.ToString() + "\"");
public bool Write(RegistryKey baseKey, string keyPath, string KeyName, object Value)
{
    try
    {
        // Setting 
        RegistryKey rk = baseKey;
        // I have to use CreateSubKey 
        // (create or open it if already exits), 
        // 'cause OpenSubKey open a subKey as read-only 
        RegistryKey sk1 = rk.CreateSubKey(keyPath);
        // Save the value 
        sk1.SetValue(KeyName.ToUpper(), Value);

        return true;
    }
    catch (Exception e)
    {
        // an error! 
        MessageBox.Show(e.Message, "Writing registry " + KeyName.ToUpper());
        return false;
    }
}

Если вы не можете настроить автозапуск приложения, попробуйте вставить этот код в манифест

<requestedExecutionLevel  level="asInvoker" uiAccess="false" />

или удалите манифест, который я нашел в моем приложении

Для WPF: (где lblInfo - метка, chkRun - флажок)

this.Topmost - просто держать мое приложение поверх других окон, вам также нужно добавить оператор использования " using Microsoft.Win32; ", StartupWithWindows - это имя моего приложения

public partial class MainWindow : Window
    {
        // The path to the key where Windows looks for startup applications
        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        public MainWindow()
        {
            InitializeComponent();
            if (this.IsFocused)
            {
                this.Topmost = true;
            }
            else
            {
                this.Topmost = false;
            }

            // Check to see the current state (running at startup or not)
            if (rkApp.GetValue("StartupWithWindows") == null)
            {
                // The value doesn't exist, the application is not set to run at startup, Check box
                chkRun.IsChecked = false;
                lblInfo.Content = "The application doesn't run at startup";
            }
            else
            {
                // The value exists, the application is set to run at startup
                chkRun.IsChecked = true;
                lblInfo.Content = "The application runs at startup";
            }
            //Run at startup
            //rkApp.SetValue("StartupWithWindows",System.Reflection.Assembly.GetExecutingAssembly().Location);

            // Remove the value from the registry so that the application doesn't start
            //rkApp.DeleteValue("StartupWithWindows", false);

        }

        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            if ((bool)chkRun.IsChecked)
            {
                // Add the value in the registry so that the application runs at startup
                rkApp.SetValue("StartupWithWindows", System.Reflection.Assembly.GetExecutingAssembly().Location);
                lblInfo.Content = "The application will run at startup";
            }
            else
            {
                // Remove the value from the registry so that the application doesn't start
                rkApp.DeleteValue("StartupWithWindows", false);
                lblInfo.Content = "The application will not run at startup";
            }
        }

    }

Приложение с открытым исходным кодом "Startup Creator" настраивает загрузку Windows, создавая сценарий и предоставляя простой в использовании интерфейс. Используя мощный VBScript, он позволяет приложениям или службам запускаться с задержкой по времени, всегда в одном и том же порядке. Эти сценарии автоматически помещаются в папку автозагрузки и могут быть открыты обратно для внесения изменений в будущем.

http://startupcreator.codeplex.com/

Хорошо, вот мои 2 цента: попробуйте пройти путь с каждым обратным слешем как двойной обратный слеш. Я обнаружил, что иногда вызов WIN API требует этого.

Я думаю, что есть специальный вызов Win32 API, который берет путь приложения и автоматически помещает его в реестр для вас в правильном месте, я использовал его в прошлом, но больше не помню имя функции.

Другие вопросы по тегам