Unity开发——开机自启动

一、导入依赖库

准备Interop.IWshRuntimeLibrary.dll,微软用来创建快捷方式的类库,导入项目中。

写脚本

以下脚本挂载到场景中,运行一次后,PC端下次开机就会自动打开你的软件了。

using System;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using IWshRuntimeLibrary;

public class KMStartRuning : MonoBehaviour
{
    public Text hintText;
    private static string ShortcutName = "KMStartRuning.lnk";

    private void Start()
    {
        isStartup();
        OnSetupStartupButtonClick();
    }

    private void OnSetupStartupButtonClick()
    {
        CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.Startup), ShortcutName, System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
        isStartup();
    }

    private void OnCancelStartupButtonClick()
    {
        if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\" + ShortcutName))
            System.IO.File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\" + ShortcutName);
        isStartup();
    }

    private void isStartup()
    {
        if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\" + ShortcutName))
            hintText.text = "应用已开机自启";
        else
            hintText.text = "应用非开机自启";
    }

    public static bool CreateShortcut(string direstory, string shortcurName, string targetPath, string description = null, string iconLocation = null)
    {

        try
        {
            if (!Directory.Exists(direstory))
            {
                Directory.CreateDirectory(direstory);
            }

            // 添加引用com中搜索Windows Script Host Object Model, 如果在unity中使用则需下载 Interop.IWshRuntimeLibrary.dll 并放到代码同一文件夹
            string shortscurPath = Path.Combine(direstory, string.Format("{0}", shortcurName));
            IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
            IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortscurPath); // 创建快捷方式对象
            shortcut.TargetPath = targetPath; // 指定目标路径
            shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath); //设置起始位置
            shortcut.WindowStyle = 1; // 设置运行方式,默认为常规窗口
            shortcut.Description = description; // 设置备注
            shortcut.IconLocation = string.IsNullOrEmpty(iconLocation) ? targetPath : iconLocation; //设置图标路径
            shortcut.Save(); // 保存快捷方式
            return true;
        }
        catch
        {

        }

        return false;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值