web-dev-qa-db-fra.com

Comment exécuter une application C # au démarrage de Windows?

J'ai créé une application qui démarre au démarrage, avec le code suivant ci-dessous.
Le processus s'exécute sur l'outil de gestion de processus après le redémarrage, mais je ne vois pas L'application à l'écran . Lorsque j'ouvre le même fichier .exe à partir de la valeur de registre de démarrage, le programme s'exécute parfaitement .

// 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());

Que puis-je faire pour le réparer?

57
bloodix

Le code est ici (application de formulaire gagnant):

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);
            }
        }
    }
}
55
Adrew

Essayez ce code

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");
    }
}

Source: http://www.dotnet Thoughts.net/2010/09/26/run-the-application-at-windows-startup/

33
Anuraj

Vous pouvez essayer de copier un raccourci vers votre application dans le dossier de démarrage au lieu d’ajouter des éléments au registre. Vous pouvez obtenir le chemin avec Environment.SpecialFolder.Startup. Ceci est disponible dans tous les frameworks .net depuis 1.1.

Sinon, peut-être que ce site vous sera utile, il répertorie de nombreuses façons différentes de faire en sorte qu'une application démarre automatiquement.

16
Phil Gan
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;
    }
}

vous pouvez vérifier toute article ici

9
Rashid Malik

j'ai d'abord essayé le code ci-dessous et cela ne fonctionnait pas

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

Ensuite, j'ai changé CurrentUser avec LocalMachine et cela fonctionne

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

Je n'ai trouvé aucun des codes ci-dessus fonctionné. C'est peut-être parce que mon application exécute .NET 3.5. Je ne sais pas. Le code suivant a parfaitement fonctionné pour moi. Je l'ai reçu d'un développeur d'applications .NET de niveau supérieur de mon équipe. 

 Write (Microsoft.Win32.Registry.LocalMachine, @ "LOGICIEL\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;
    }
}
1
user1000008

1- ajouter un espace de noms:

using Microsoft.Win32;

2-add application pour vous inscrire:

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

3-si vous voulez supprimer une application du registre:

key.DeleteValue("your_app_name",false);
0
mamal

Une application open source appelée "Startup Creator" configure le démarrage de Windows en créant un script tout en offrant une interface facile à utiliser. Utilisant un puissant VBScript, il permet aux applications ou aux services de démarrer à des intervalles temporisés, toujours dans le même ordre. Ces scripts sont automatiquement placés dans votre dossier de démarrage et peuvent être ouverts pour permettre des modifications ultérieures.

http://startupcreator.codeplex.com/

0
Jake Soenneker

Si vous ne pouvez pas définir le démarrage automatique de votre application, vous pouvez essayer de coller ce code dans Manifest

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

ou supprimer le manifeste je l'avais trouvé dans ma demande

0
William Wild

pour WPF: (où lblInfo est une étiquette, chkRun est une checkBox)

this.Topmost consiste simplement à conserver mon application au-dessus des autres fenêtres. Vous devrez également ajouter une instruction using " using Microsoft.Win32; ", StartupWithWindows est le nom de mon application.

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";
            }
        }

    }
0
shakram02