【问题标题】:How to run a C# application at Windows startup (update)?如何在 Windows 启动(更新)时运行 C# 应用程序?
【发布时间】:2019-01-31 12:09:08
【问题描述】:

我想在启动时运行 C# 应用程序。我使用了这段代码,我找到了here

private void SetStartup(bool enable)
    {
        string runKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

        RegistryKey startupKey = Registry.CurrentUser.OpenSubKey(runKey);

        if (enable)
        {
            if (startupKey.GetValue("ZanNews") == null)
            {
                startupKey.Close();
                startupKey = Registry.CurrentUser.OpenSubKey(runKey, true);
                startupKey.SetValue("ZanNews", "\"" + Application.ExecutablePath + "\"");
                startupKey.Close();
            }
        }
        else
        {
            startupKey = Registry.CurrentUser.OpenSubKey(runKey, true);
            startupKey.DeleteValue("ZanNews", false);
            startupKey.Close();
        }
    }

虽然该条目出现在注册表和任务管理器中,但该程序不会随 Windows 一起启动。

在问这个问题之前,我对 StackOverflow 进行了先前的研究,但提出的解决方案和代码 sn-ps herehere 都不起作用。要么我收到安全和访问错误消息,要么已写入注册表,但程序拒绝从操作系统启动。然而,我看到上述问题是在 2010 年和 2011 年提出的,我认为从那时起情况发生了变化。

有没有办法让程序在启动时运行?我在 2018 年 4 月 10 日更新的 Windows 上安装了 Windows 10 家庭版 1803 版和 .NET Framework 4.7.2。

稍后编辑:其他信息:

  1. Application.ExecutablePath的值为C:\\Users\\alexz\\OneDrive\\Programe\\C#/ZanScore/ZanScore/bin/Debug/ZanNews.exe"
  2. 我尝试删除“#”字符,但没有成功;
  3. 注册表编辑器屏幕截图:
  4. 任务管理器的屏幕截图(罗马尼亚语):

【问题讨论】:

  • 你的跑得怎么样 SetStartup?
  • 请在您的命令提示符问题中附上屏幕截图,该命令提示符已在C:\\Users\\alexz\\OneDrive\\Programe\\C#/ZanScore/ZanScore/bin/Debug/ 中运行dir(即向我们证明该文件夹存在,并且其中的可执行文件)。

标签: c# .net registry startup


【解决方案1】:

做了一些研究,我发现创建快捷方式并将其放在Startup 文件夹中是一种更好的方法。 here 提供了更多详细信息,代码(有效并解决了问题)是:

        WshShell wshShell = new WshShell();
        IWshRuntimeLibrary.IWshShortcut shortcut;
        string startUpFolderPath =
          Environment.GetFolderPath(Environment.SpecialFolder.Startup);

        // Create the shortcut
        shortcut =
          (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(
            startUpFolderPath + "\\" +
            Application.ProductName + ".lnk");

        shortcut.TargetPath = Application.ExecutablePath;
        shortcut.WorkingDirectory = Application.StartupPath;
        shortcut.Description = "Launch My Application";
        // shortcut.IconLocation = Application.StartupPath + @"\App.ico";
        shortcut.Save();

为了能够使用上述代码,您需要包含IWshRuntimeLibrary 命名空间并将Windows 脚本宿主对象模型 引用添加到项目中。

其他参考是here

【讨论】:

    猜你喜欢
    • 2011-07-02
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2011-08-22
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多