在用户的启动文件夹中放置一个快捷方式以随Windows一起启动

10

我想给我的用户提供一个“开机启动”选项。当用户勾选此选项时,它将在启动文件夹中放置一个快捷方式图标(而非注册表)。

在Windows重新启动时,它会自动加载我的应用程序。

如何实现这个功能?

3个回答

17

你可以使用Enviroment.SpecialFolder枚举,不过根据你的需求,你可能需要考虑创建一个Windows服务来取代一个必须在启动时运行的应用程序。

File.Copy("shortcut path...", Environment.GetFolderPath(Environment.SpecialFolder.Startup) + shorcutname);

编辑:

File.Copy需要一个原始文件目录路径和目标目录路径来复制文件。该代码片段中的关键是Enviroment.GetFolderPath(Enviroment.SpecialFolder.Startup),它获取了启动文件夹路径,您可以将文件复制到该路径下。

你可以使用上面的代码多种方式。如果您的应用程序有安装程序项目,您可以在安装时运行类似以下内容的代码。另一种方法是在应用程序启动时检查快捷方式是否存在,如果不存在,则将其放置在那里(通过File.Exists())。

这里 是一个有关在代码中创建快捷方式的问题。


5
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"的引用,请在COM下选择"Windows Script Host Object Model"。 - Rado

-1
private void button2_Click(object sender, EventArgs e)
        {
            string pas = Application.StartupPath;
            string sourcePath = pas;
            string destinationPath = @"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup";
            string sourceFileName = "filename.txt";//eny tipe of file
            string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
            string destinationFile = System.IO.Path.Combine(destinationPath);

            if (!System.IO.Directory.Exists(destinationPath))
            {
                System.IO.Directory.CreateDirectory(destinationPath);
            }
            System.IO.File.Copy(sourceFile, destinationFile, true);



        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接