C# 如何设置程序在启动时启动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/674628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:55:34  来源:igfitidea点击:

How do I set a program to launch at startup

c#windows

提问by Spidey

I have a small application with a CheckBoxoption that the user can set if they want the app to start with Windows.

我有一个带有CheckBox选项的小应用程序,如果用户希望应用程序从 Windows 启动,可以设置该选项。

My question is how do I actually set the app to run at startup.

我的问题是我如何实际设置应用程序在启动时运行。

ps: I'm using C# with .NET 2.0.

ps:我在 .NET 2.0 中使用 C#。

采纳答案by Joel Coehoorn

Several options, in order of preference:

多个选项,按优先顺序排列:

  1. Add it to the current user's Startup folder. This requires the least permissions for your app to run, and gives the user the most control and feedback of what's going on. The down-side is it's a little more difficult determining whether to show the checkbox already checked next time they view that screen in your program.
  2. Add it to the HKey_Current_User\Software\Microsoft\Windows\CurrentVersion\Runregistry key. The only problem here is it requires write access to the registry, which isn't always available.
  3. Create a Scheduled Task that triggers on User Login
  4. Add it to the HKey_Local_Machine\Software\Microsoft\Windows\CurrentVersion\Runregistry key. The only problem here is it requires write access to the registry, which isn't always available.
  5. Set it up as a windows service. Only do this if you reallymean it, andyou know for sure you want to run this program for allusers on the computer.
  1. 将其添加到当前用户的启动文件夹中。这需要您的应用程序运行的最少权限,并为用户提供对正在发生的事情的最大控制和反馈。不利的一面是,确定下次他们在您的程序中查看该屏幕时是否显示已选中的复选框有点困难。
  2. 将其添加到HKey_Current_User\Software\Microsoft\Windows\CurrentVersion\Run注册表项。这里唯一的问题是它需要对注册表的写访问权限,这并不总是可用。
  3. 创建在用户登录时触发的计划任务
  4. 将其添加到HKey_Local_Machine\Software\Microsoft\Windows\CurrentVersion\Run注册表项。这里唯一的问题是它需要对注册表的写访问权限,这并不总是可用。
  5. 将其设置为 Windows 服务。仅当您确实认真的并且您确定要为计算机上的所有用户运行此程序时才这样做。

This answer is older now. Since I wrote this, Windows 10 was released, which changes how the Start Menu folders work... including the Startupfolder. It's not yet clear to me how easy it is to just add or remove a file in that folder without also referencing the internal database Windows uses for these locations.

这个答案现在更旧了。自从我写这篇文章以来,Windows 10 已经发布,它改变了开始菜单文件夹的工作方式......包括Startup文件夹。我还不清楚在该文件夹中添加或删除文件而不参考 Windows 用于这些位置的内部数据库是多么容易。

回答by Jon Tackabury

You can create a registry entry in "HKCU\Software\Microsoft\Windows\CurrentVersion\Run", just be aware that it may work differently on Vista. Your setting might get "virtualized" because of UAC.

您可以在“HKCU\Software\Microsoft\Windows\CurrentVersion\Run”中创建一个注册表项,请注意它在 Vista 上的工作方式可能有所不同。由于 UAC,您的设置可能会“虚拟化”。

回答by Harper Shelby

If an application is designed to start when Windows starts (as opposed to when a user logs in), your only option is to involve a Windows Service. Either write the application as a service, or write a simple service that exists only to launch the application.

如果应用程序设计为在 Windows 启动时启动(而不是在用户登录时启动),则您唯一的选择是使用 Windows 服务。要么将应用程序编写为服务,要么编写一个仅用于启动应用程序的简单服务。

Writing services can be tricky, and can impose restrictions that may be unacceptable for your particular case. One common design pattern is a front-end/back-end pair, with a service that does the work and an application front-end that communicates with the service to display information to the user.

编写服务可能很棘手,并且可能会施加一些限制,这对于您的特定情况可能是不可接受的。一种常见的设计模式是前端/后端对,其中一个服务完成工作,一个应用程序前端与该服务通信以向用户显示信息。

On the other hand, if you just want your application to start on user login, you can use methods 1 or 2 that Joel Coehoorn listed.

另一方面,如果您只希望您的应用程序在用户登录时启动,您可以使用 Joel Coehoorn 列出的方法 1 或 2。

回答by Spidey

Thanks to everyone for responding so fast. Joel, I used your option 2 and added a registry key to the "Run" folder of the current user. Here's the code I used for anyone else who's interested.

感谢大家这么快回复。乔尔,我使用了您的选项 2,并在当前用户的“运行”文件夹中添加了一个注册表项。这是我用于其他感兴趣的人的代码。

    using Microsoft.Win32;
    private void SetStartup()
    {
        RegistryKey rk = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);

        if (chkStartUp.Checked)
            rk.SetValue(AppName, Application.ExecutablePath);
        else
            rk.DeleteValue(AppName,false);            

    }

回答by Aldwin Nunag

You can do this with the win32 class in the Microsoft namespace

您可以使用 Microsoft 命名空间中的 win32 类来执行此操作

using Microsoft.Win32;

using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true))
 {
            key.SetValue("aldwin", "\"" + Application.ExecutablePath + "\"");
 }

回答by INS software

    /// <summary>
    /// Add application to Startup of windows
    /// </summary>
    /// <param name="appName"></param>
    /// <param name="path"></param>
    public static void AddStartup(string appName, string path)
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true))
        {
            key.SetValue(appName, "\"" + path + "\"");
        }
    }

    /// <summary>
    /// Remove application from Startup of windows
    /// </summary>
    /// <param name="appName"></param>
    public static void RemoveStartup(string appName)
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true))
        {
            key.DeleteValue(appName, false);
        }
    }

回答by Xepher Dotcom

Here is all way to add your program to startup for Windows Vista, 7, 8, 10

这是将您的程序添加到 Windows Vista、7、8、10 启动程序的所有方法

  • File path

C:\Users\Bureau Briffault\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup(Visible from task manager, Running on current user login success, No admin privileges required)

C:\Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup(Visible from task manager, Running on all user login success, Admin privileges required)

  • 文件路径

C:\Users\Bureau Briffault\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup(从任务管理器可见,在当前用户登录成功时运行,无需管理员权限)

C:\Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup(在任务管理器中可见,所有用户登录成功时运行,需要管理员权限)



  • Registry path

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run(Visible from task manager, Running on current user login success, No admin privileges required)

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce(Not visible from task manager, Running on current user login success, Running for one login time, No admin privileges required)

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run(Visible from task manager, Running on all user login success, Admin privileges required)

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce(Not visible from task manager, Running on all user login success, Running for one login time, Admin privileges required)

  • 注册表路径

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run(从任务管理器可见,在当前用户登录成功时运行,无需管理员权限)

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce(在任务管理器中不可见,在当前用户登录成功时运行,运行一次登录时间,无需管理员权限)

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run(在任务管理器中可见,所有用户登录成功时运行,需要管理员权限)

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce(在任务管理器中不可见,在所有用户登录成功时运行,运行一次登录时间,需要管理员权限)



  • Task scheduler

Microsoft.Win32.Taskscheduler.dll(Not visible from task manager, Running on windows boot, Running as admin, Admin privileges required)

  • 任务调度器

Microsoft.Win32.Taskscheduler.dll(在任务管理器中不可见,在 Windows 启动时运行,以管理员身份运行,需要管理员权限)

回答by Krzysiek

In addition to Xepher Dotcom's answer, folder path to Windows Startup should be coded that way:

除了 Xepher Dotcom 的回答之外,Windows Startup 的文件夹路径应该这样编码:

var Startup = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

回答by Mohammad Fathi MiMFa

It`s a so easy solution:

这是一个如此简单的解决方案:

To Add

加上

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

To Remove

去除

Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
key.DeleteValue("Your Application Name", false);

回答by gcdev

I found adding a shortcut to the startup folder to be the easiest way for me. I had to add a reference to "Windows Script Host Object Model" and "Microsoft.CSharp" and then used this code:

我发现向启动文件夹添加快捷方式对我来说是最简单的方法。我必须添加对“Windows Script Host Object Model”和“Microsoft.CSharp”的引用,然后使用以下代码:

IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
string shortcutAddress = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\MyAppName.lnk";
System.Reflection.Assembly curAssembly = System.Reflection.Assembly.GetExecutingAssembly();

IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "My App Name";
shortcut.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
shortcut.TargetPath = curAssembly.Location;
shortcut.IconLocation = AppDomain.CurrentDomain.BaseDirectory + @"MyIconName.ico";
shortcut.Save();