随笔 - 317, 文章 - 0, 评论 - 453, 阅读 - 114万
  博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

C# 快捷方式 自启动

Posted on   PHP-张工  阅读(4407)  评论(2编辑  收藏  举报

C#创建快捷方式

需要先引用COM组件 Interop.IWshRuntimeLibrary.dll 如下图

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private void CreateLnk(string lnkPath)
{
    if (!System.IO.File.Exists(lnkPath))
    {
        IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
        IWshRuntimeLibrary.IWshShortcut shortCut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(lnkPath);
        shortCut.TargetPath = Application.ExecutablePath;
        shortCut.WindowStyle = 1;
        shortCut.Description = Application.ProductName + Application.ProductVersion;
        shortCut.IconLocation = Application.ExecutablePath;
        shortCut.WorkingDirectory = Application.StartupPath;
        shortCut.Save();
    }
}

获取桌面路径

1
string lnkPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + Application.ProductName + ".lnk";

获取启动文件夹路径

1
string lnkPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\" + Application.ProductName + ".lnk";

 

操作注册表实现自启动

操作方法就是给注册表的 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run 添加程序路径

1
2
3
RegistryKey key = Registry.LocalMachine;
key = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
key.SetValue(Application.ProductName, Application.ExecutablePath);

注意此方法在Win7下测试报错!System.UnauthorizedAccessException: 试图执行未经授权的操作。


创建URL快捷方式

1
2
3
4
5
6
7
string deskDir = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
using (StreamWriter writer = new StreamWriter(deskDir + "\\aaaa.url"))
{
    writer.WriteLine("[InternetShortcut]");
    writer.WriteLine("URL=http://www.163.com/");
    writer.Flush();
}

 

示例下载:https://files.cnblogs.com/zjfree/linkTo.rar

运行环境:WIN2003 + VS2005

努力加载评论中...
点击右上角即可分享
微信分享提示