unity发布EXE后,打包程序开机自启代码

using System;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using IWshRuntimeLibrary;
public class StartMenu : MonoBehaviour
{

public Button setupStartupButton;
public Button cancelStartupButton;
public Text hintText;
private static string ShortcutName = "test.lnk";

private void OnEnable()
{
    isStartup();
    //OnSetupStartupButtonClick();
    setupStartupButton.onClick.AddListener(OnSetupStartupButtonClick);
    cancelStartupButton.onClick.AddListener(OnCancelStartupButtonClick);
}

private void OnDisable()
{
    setupStartupButton.onClick.RemoveListener(OnSetupStartupButtonClick);
    cancelStartupButton.onClick.RemoveListener(OnCancelStartupButtonClick);
}

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

}

所需 Interop.IWshRuntimeLibrary.dll 百度云链接
密码:dnoi

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值