简体   繁体   English

如何在 Windows 启动时运行 C# 应用程序?

[英]How to run a C# application at Windows startup?

I made an application that launches during startup, with the next code below.我制作了一个在启动期间启动的应用程序,下面是下一个代码。
The process runs on the process manager tool after the restart, but I can't see the application on the screen.重启后进程在进程管理器工具上运行,但是在屏幕上看不到应用程序。 When I open the same.exe file from the startup registry value the program runs perfect.当我从启动注册表值打开 same.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());

What can I do to fix it up?我能做些什么来修复它?

Code is here (Win form app):代码在这里(Win 表单应用程序):

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

Try this 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 (dead): http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/来源(已死): http : //www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/

Archived link: https://web.archive.org/web/20110104113608/http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/存档链接: https ://web.archive.org/web/20110104113608/http: //www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/

You could try copying a shortcut to your application into the startup folder instead of adding things to the registry.您可以尝试将应用程序的快捷方式复制到启动文件夹中,而不是将内容添加到注册表中。 You can get the path with Environment.SpecialFolder.Startup .您可以使用Environment.SpecialFolder.Startup获取路径。 This is available in all .net frameworks since 1.1.自 1.1 以来,这在所有 .net 框架中都可用。

Alternatively, maybe this site will be helpful to you, it lists a lot of the different ways you can get an application to auto-start.或者,也许这个站点会对您有所帮助,它列出了许多可以让应用程序自动启动的不同方法。

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

you can check whole article here你可以在这里查看整篇文章

its very simple非常简单

add two part in code :在代码中添加两部分:

1- add namespace : 1-添加命名空间

using Microsoft.Win32;

2- add application to registery : 2-将应用程序添加到注册:

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

if you want delete app from registery :如果您想从注册中删除应用程序

key.DeleteValue("your_app_name",false);

I did not find any of the above code worked.我没有发现任何上述代码有效。 Maybe that's because my app is running .NET 3.5.也许那是因为我的应用程序运行的是 .NET 3.5。 I don't know.我不知道。 The following code worked perfectly for me.以下代码非常适合我。 I got this from a senior level .NET app developer on my team.我从我团队的高级 .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;
    }
}

first I tried the code below and it was not working首先我尝试了下面的代码,但它不起作用

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

Then, I changed CurrentUser with LocalMachine and it works然后,我用 LocalMachine 更改了 CurrentUser 并且它可以工作

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

An open source application called "Startup Creator" configures Windows Startup by creating a script while giving an easy to use interface.一个名为“Startup Creator”的开源应用程序通过创建脚本来配置 Windows 启动,同时提供易于使用的界面。 Utilizing powerful VBScript, it allows applications or services to start up at timed delay intervals, always in the same order.利用强大的 VBScript,它允许应用程序或服务以定时的延迟间隔启动,始终以相同的顺序启动。 These scripts are automatically placed in your startup folder, and can be opened back up to allow modifications in the future.这些脚本会自动放置在您的启动文件夹中,并且可以打开备份以供日后修改。

http://startupcreator.codeplex.com/ http://startupcreator.codeplex.com/

for WPF: (where lblInfo is a label, chkRun is a checkBox)对于 WPF:(其中 lblInfo 是一个标签,chkRun 是一个复选框)

this.Topmost is just to keep my app on the top of other windows, you will also need to add a using statement " using Microsoft.Win32; ", StartupWithWindows is my application's name this.Topmost 只是为了让我的应用程序保持在其他窗口的顶部,您还需要添加一个 using 语句“ 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";
            }
        }

    }

If you could not set your application autostart you can try to paste this code to manifest如果您无法设置应用程序自动启动,您可以尝试将此代码粘贴到清单

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

or delete manifest I had found it in my application或删除我在应用程序中找到的清单

我认为有一个特定的 Win32 API 调用,它采用应用程序路径并将其自动放入注册表中的适当位置,我过去曾使用过它,但我不再记得函数名称了。

OK here are my 2 cents: try passing path with each backslash as double backslash.好的,这是我的 2 美分:尝试将每个反斜杠作为双反斜杠传递路径。 I have found sometimes calling WIN API requires that.我发现有时调用 WIN API 需要这样做。

I want at startup it run the app on 2nd monitor, Is there any way, help me.我想在启动时在第二台显示器上运行应用程序,有什么办法,帮帮我。 (The computer I connect 2 monitors to) (我连接2个显示器的电脑)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM