Как запустить приложение С# при запуске 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());
Что я могу сделать, чтобы исправить это?
Ответы
Ответ 1
Код здесь (приложение для формы выигрыша):
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);
}
}
}
}
Ответ 2
Попробуйте этот код
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.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/
Ответ 3
Вы можете попробовать скопировать ярлык в приложение в папку автозагрузки вместо добавления в реестр. Вы можете получить путь с помощью Environment.SpecialFolder.Startup
. Это доступно во всех инфраструктурах .net начиная с версии 1.1.
В качестве альтернативы, возможно, этот сайт будет вам полезен, он перечисляет множество различных способов, которыми вы можете получить приложение для автоматического запуска.
Ответ 4
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;
}
}
вы можете проверить целую статью здесь
Ответ 5
1- добавить пространство имен:
using Microsoft.Win32;
2-добавить приложение для регистрации:
RegistryKey key=Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("your_app_name", Application.ExecutablePath);
если вы хотите удалить приложение из реестра:
key.DeleteValue("your_app_name",false);
Ответ 6
Я не нашел ни одного из вышеуказанного кода. Может быть, потому, что в моем приложении работает .NET 3.5. Я не знаю. Следующий код работал отлично для меня. Я получил это от разработчика .NET на уровне старшего уровня в моей команде.
Write(Microsoft.Win32.Registry.LocalMachine, @"SOFTWARE\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;
}
}
Ответ 7
сначала я попробовал код ниже, и он не работал
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());
Ответ 8
Приложение с открытым исходным кодом под названием "Startup Creator" настраивает запуск Windows, создавая script, предоставляя простой в использовании интерфейс. Используя мощный VBScript, он позволяет запускать приложения или службы с временными интервалами задержки, всегда в том же порядке. Эти сценарии автоматически помещаются в вашу папку автозагрузки и могут быть открыты обратно, чтобы в будущем вносить изменения.
http://startupcreator.codeplex.com/
Ответ 9
для WPF: (где lblInfo - это метка, chkRun - checkBox)
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";
}
}
}
Ответ 10
Если вы не можете настроить автозапуск приложения, вы можете попробовать вставить этот код в манифест
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
или удалить манифест, я нашел его в своем приложении
Ответ 11
Я думаю, что есть определенный вызов API Win32, который принимает путь к программе и автоматически помещает его в реестр для вас в нужном месте, я использовал его в прошлом, но я больше не помню имя функции.
Ответ 12
ОК, вот мои 2 цента: попробуйте проложить путь с каждой обратной косой чертой в виде двойной обратной косой черты. Я обнаружил, что иногда вызов WIN API требует этого.