public static string CreateShortcut() { ShellLink link = new ShellLink(); IShellLinkW shellLink = (IShellLinkW)link; shellLink.SetPath(System.Windows.Forms.Application.ExecutablePath); shellLink.SetWorkingDirectory(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath)); shellLink.SetIconLocation(System.Windows.Forms.Application.ExecutablePath, 0); string dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), ((GuidAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), true)[0]).Value); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } string linkFilename = System.IO.Path.Combine(dir, string.Format("{0}.lnk", System.Windows.Forms.Application.ProductName)); if (System.IO.File.Exists(linkFilename)) { System.IO.File.Delete(linkFilename); } IPersistFile c = (IPersistFile)link; c.Save(linkFilename, false); return(linkFilename); }
public static IShellLink Create() { ShellLink link = new ShellLink(); IShellLink shellLink = (IShellLink)link; return(shellLink); }
private void updateStartMenu(string startMenu, string oldFullPath, string newFullPath) { string oldName = Path.GetFileNameWithoutExtension(oldFullPath); string newName = Path.GetFileNameWithoutExtension(newFullPath); string linkName = startMenu + "\\" + oldName + "\\" + oldName + ".lnk"; if (!File.Exists(linkName)) { return; } ShellLink shortcut = new ShellLink(linkName); if (Path.GetFullPath(shortcut.Target).ToLower() != oldFullPath.ToLower()) { return; /* doesn't refer to us therefore we don't care */ } try { shortcut.Target = newFullPath; shortcut.WorkingDirectory = Path.GetDirectoryName(newFullPath); shortcut.Description = newName; shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; shortcut.Save(); File.Move(linkName, startMenu + "\\" + oldName + "\\" + newName + ".lnk"); Directory.Move(startMenu + "\\" + oldName, startMenu + "\\" + newName); } catch {}; }
public static void AddToStartup() { string StartupDirectory = Environment.GetFolderPath( Environment.SpecialFolder.Startup); string LNKName = "\\IPInformer.lnk"; string Target = Application.ExecutablePath; string WorkDir = Application.StartupPath; ShellLink shortcut = new ShellLink(); shortcut.ShortCutFile = StartupDirectory + LNKName; shortcut.Target = Target; shortcut.WorkingDirectory = WorkDir; shortcut.IconPath = Target; shortcut.IconIndex = 0; shortcut.Description = "IP Informer"; if (CommonFunctions.NoPortable) { shortcut.Arguments = "/np"; } else { shortcut.Arguments = ""; } shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; shortcut.Save(); }
private DesktopApp(string name, string executionPath) { if (String.IsNullOrEmpty(name)) { throw new ArgumentException("name"); } if (String.IsNullOrEmpty(executionPath)) { throw new ArgumentException("executionPath"); } this.name = name; if (Path.GetExtension(executionPath) == ".lnk") { var targetPath = new ShellLink(executionPath).TargetPath; if (targetPath != null && targetPath.Length > 0) { executionPath = targetPath; } } this.executionPath = executionPath; }
/// <summary> /// /// </summary> protected override void ProcessRecord() { //WriteObject(ForensicTimeline.GetInstances(Prefetch.GetInstances(volume)), true); WriteVerbose("Getting ScheduledJob Instances"); WriteObject(ForensicTimeline.GetInstances(ScheduledJob.GetInstances(volume)), true); WriteVerbose("Getting ShellLink Instances"); WriteObject(ForensicTimeline.GetInstances(ShellLink.GetInstances(volume)), true); WriteVerbose("Getting FileRecord Instances"); WriteObject(ForensicTimeline.GetInstances(FileRecord.GetInstances(volume)), true); WriteVerbose("Getting UsnJrnl Instances"); WriteObject(ForensicTimeline.GetInstances(UsnJrnl.GetInstances(volume)), true); WriteVerbose("Getting EventRecord Instances"); WriteObject(ForensicTimeline.GetInstances(EventRecord.GetInstances(volume)), true); WriteVerbose("Getting DRIVERS Hive Keys"); WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\DRIVERS")), true); WriteVerbose("Getting SAM Hive Keys"); WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SAM")), true); WriteVerbose("Getting SECURITY Hive Keys"); WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SECURITY")), true); WriteVerbose("Getting SOFTWARE Hive Keys"); WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SOFTWARE")), true); WriteVerbose("Getting SYSTEM Hive Keys"); WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SYSTEM")), true); }
public static void Create(string original, string shortcut, string comment = null) { if (string.IsNullOrWhiteSpace(original)) { throw new ArgumentException("", "original"); } if (string.IsNullOrWhiteSpace(shortcut)) { throw new ArgumentException("", "shortcut"); } if (!shortcut.EndsWith(".lnk", StringComparison.InvariantCultureIgnoreCase)) { shortcut += ".lnk"; } var shellLink = new ShellLink(); // cocreate instance var ishellLink = (IShellLinkW)shellLink; // query interface var ipersistFile = (IPersistFile)shellLink; // query interface try { // Set the path to the shortcut target and add the description. ishellLink.SetPath(original); ishellLink.SetDescription(comment); // Save the link by calling IPersistFile::Save. ipersistFile.Save(shortcut, true); } finally { Marshal.ReleaseComObject(ishellLink); Marshal.ReleaseComObject(ipersistFile); Marshal.ReleaseComObject(shellLink); } }
private string ResolveExecuteable(string filename, out string profileName) { var fileInfo = new FileInfo(filename); profileName = fileInfo.Name.Substring(0, fileInfo.Name.Length - fileInfo.Extension.Length); if (fileInfo.Extension.ToLower().Equals(".lnk")) { try { var shellLink = new ShellLink(filename); var targetInfo = new FileInfo(shellLink.Target); if (targetInfo.Extension.ToLower().Equals(".exe")) { return(targetInfo.Name); } return(""); } catch { return(""); } } if (fileInfo.Extension.ToLower().Equals(".exe")) { return(fileInfo.Name); } return(""); }
public static WindowsApplicationContext FromCurrentProcess( string?customName = null, string?appUserModelId = null) { var mainModule = Process.GetCurrentProcess().MainModule; var appName = customName ?? Path.GetFileNameWithoutExtension(mainModule.FileName); var aumid = appUserModelId ?? appName; //TODO: Add seeded bits to avoid collisions? SetCurrentProcessExplicitAppUserModelID(aumid); using var shortcut = new ShellLink { TargetPath = mainModule.FileName, Arguments = string.Empty, AppUserModelID = aumid }; var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); var startMenuPath = Path.Combine(appData, @"Microsoft\Windows\Start Menu\Programs"); var shortcutFile = Path.Combine(startMenuPath, $"{appName}.lnk"); shortcut.Save(shortcutFile); return(new WindowsApplicationContext(appName, aumid)); }
public static Option <string> CreateShortcut(Some <string> shortcutPath, Some <string> path, Option <string> arguments, Some <string> description, bool force) { if (File.Exists(shortcutPath.Value) && !force) { return(new Option <string>(shortcutPath)); } if (File.Exists(shortcutPath.Value)) { File.Delete(shortcutPath.Value); } // ReSharper disable once SuspiciousTypeConversion.Global var link = new ShellLink() as IShellLink; // setup shortcut information link?.SetDescription(description.Value); link?.SetPath(path.Value); arguments.IfSome(a => link?.SetArguments(a)); // save it // ReSharper disable once SuspiciousTypeConversion.Global var file = link as IPersistFile; file?.Save(shortcutPath, false); return(!File.Exists(shortcutPath.Value) ? Option <string> .None : new Option <string>(shortcutPath)); }
public void Load(string fileName) { if (_shellLink == null) { _shellLink = new ShellLink(); ((IPersistFile)_shellLink).Load(fileName, Shell.STGM_READ); var sb = new StringBuilder(Shell.MAX_PATH); var link = ((IShellLinkW)_shellLink); link.GetArguments(sb, sb.Capacity); _arguments = sb.ToString(); link.GetDescription(sb, sb.Capacity); _description = sb.ToString(); link.GetHotkey(out _hotKey); int pilcon; link.GetIconLocation(sb, sb.Capacity, out pilcon); _iconLocation = sb.ToString(); //link.GetPath(); link.GetIDList(out _idList); link.GetShowCmd(out _showCommand); link.GetWorkingDirectory(sb, sb.Capacity); _workingDirectory = sb.ToString(); } }
/// <summary>Creates a shortcut on the system.</summary> /// <param name="shortcut">The shortcut data used to create the shortcut.</param> public static void CreateShortcut(Shortcut shortcut) { if (shortcut == null) { throw new ArgumentNullException(@"shortcut"); } var shellLink = new ShellLink(); var link = (IShellLink)shellLink; link.SetArguments(shortcut.arguments); if (shortcut.Description.Count > 0) { link.SetDescription(Utilities.GetLocaleString(shortcut.Description)); } if (!string.IsNullOrWhiteSpace(shortcut.Icon)) { string[] icon = shortcut.Icon.Split(new[] { ',' }); link.SetIconLocation(icon[0], Convert.ToInt32(icon[1], CultureInfo.InvariantCulture)); } link.SetWorkingDirectory(Path.GetDirectoryName(shortcut.Target)); link.SetPath(shortcut.Target); var persistFile = (IPersistFile)link; persistFile.Save(Path.Combine(shortcut.Location, Utilities.GetLocaleString(shortcut.Name) + ".lnk"), false); Marshal.ReleaseComObject(persistFile); Marshal.ReleaseComObject(link); Marshal.ReleaseComObject(shellLink); // NativeMethods.CoInitializeEx((IntPtr)null, NativeMethods.CoInit.ApartmentThreaded); }
/// <summary> /// Gets the link path from a pinned item based on its file path. /// </summary> /// <param name="path"> /// The file to get the link. /// </param> public static string GetPinLink(string path) { var file = PathEx.Combine(path); var dir = PathEx.Combine(Environment.SpecialFolder.ApplicationData, "Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar"); foreach (var link in DirectoryEx.EnumerateFiles(dir, "*.lnk")) { var target = ShellLink.GetTarget(link); if (string.IsNullOrEmpty(target)) { continue; } if (target.StartsWith("%", StringComparison.Ordinal)) { target = PathEx.Combine(target); } if (!File.Exists(target)) { continue; } if (target.EqualsEx(file)) { return(link); } } return(null); }
private void AddNewItem() { NewItem newItem = new NewItem(); this.InsertItem(newItem, 0); newItem.AddNewItem += (sender, e) => { using (NewLnkFileDialog dlg = new NewLnkFileDialog()) { dlg.FileFilter = $"{AppString.Dialog.Program}|*.exe;*.bat;*.cmd;*.vbs;*.vbe;*.js;*.jse;*.wsf"; if (dlg.ShowDialog() != DialogResult.OK) { return; } string lnkPath = $@"{SendToPath}\{ObjectPath.RemoveIllegalChars(dlg.ItemText)}.lnk"; lnkPath = ObjectPath.GetNewPathWithIndex(lnkPath, ObjectPath.PathType.File); using (ShellLink shellLink = new ShellLink(lnkPath)) { shellLink.TargetPath = dlg.ItemFilePath; shellLink.WorkingDirectory = Path.GetDirectoryName(dlg.ItemFilePath); shellLink.Arguments = dlg.Arguments; shellLink.Save(); } DesktopIni.SetLocalizedFileNames(lnkPath, dlg.ItemText); this.InsertItem(new SendToItem(lnkPath), 2); } }; }
public bool ResolveShortcut(string shortcut, out string filepath, out string arguments) { ShellLink link = new ShellLink(); ((IPersistFile)link).Load(shortcut, STGM_READ); // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. // ((IShellLinkW)link).Resolve(hwnd, 0) StringBuilder path = new StringBuilder(MAX_PATH); WIN32_FIND_DATAW data = new WIN32_FIND_DATAW(); ((IShellLinkW)link).GetPath(path, path.Capacity, out data, 0); StringBuilder args = new StringBuilder(MAX_PATH); ((IShellLinkW)link).GetArguments(args, args.Capacity); filepath = path.ToString(); arguments = args.ToString(); if (!File.Exists(filepath)) { return(false); } return(true); }
public Settings(string name, string arg) : base(name) { _settingsCount++; if (_settingsLnk == null) { _settingsLnk = Path.GetTempFileName(); lock (SettingsLnkLock) { using (ShellLink shortcut = new ShellLink()) { shortcut.Target = Directory.GetCurrentDirectory() + "\\Resurces\\VKDriveSettings.exe"; shortcut.Arguments = arg; shortcut.WorkingDirectory = ""; shortcut.Description = "Настройки VKDrive"; shortcut.DisplayMode = ShellLink.LinkDisplayMode.EdmNormal; shortcut.Save(_settingsLnk); } } } LastWriteTime = DateTime.Now; CreationTime = DateTime.Now; LastAccessTime = DateTime.Now; Length = (new FileInfo(_settingsLnk)).Length; }
public void OnCreateShortcut(object sender, BootEntryEventArgs e) { string message = string.Format("Do you want to create a shortcut to {0} WITHOUT reboot confirmation?", e.BootEntry.Name); var status = MessageBox.Show(message, "Reboot confirmation", MessageBoxButton.YesNoCancel, MessageBoxImage.Question, MessageBoxResult.Cancel); if (status == MessageBoxResult.Cancel) { return; } SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.FileName = string.Join(string.Empty, e.BootEntry.Name.Split(Path.GetInvalidFileNameChars())); saveFileDialog.Filter = "Shortcut (*.lnk)|*.lnk"; if (saveFileDialog.ShowDialog() == true) { using (ShellLink shortcut = new ShellLink()) { shortcut.Target = System.Reflection.Assembly.GetExecutingAssembly().Location; shortcut.WorkingDirectory = Path.GetDirectoryName(shortcut.Target); shortcut.Description = string.Format("Boot to {0}", e.BootEntry.Name); shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; if (status == MessageBoxResult.Yes) { shortcut.Arguments = string.Format("{0} quiet", e.BootEntry.Id); } else { shortcut.Arguments = string.Format("{0}", e.BootEntry.Id); } shortcut.Save(saveFileDialog.FileName); } } }
public static IShellLink Create(string folderPath, string name, string target, string description = "", string arguments = "", string workingDirectory = "", string iconPath = "", int iconIndex = -1) { var shortcut = new ShellLink() as IShellLink; if (shortcut != null && !string.IsNullOrEmpty(target) && !string.IsNullOrEmpty(name)) { // setup shortcut information shortcut.SetPath(target); if (!string.IsNullOrEmpty(description)) { shortcut.SetDescription(description); } if (!string.IsNullOrEmpty(iconPath) && iconIndex >= 0) { shortcut.SetIconLocation(iconPath, iconIndex); } if (!string.IsNullOrEmpty(arguments)) { shortcut.SetArguments(arguments); } if (!string.IsNullOrEmpty(workingDirectory)) { shortcut.SetWorkingDirectory(workingDirectory); } // save it var file = (IPersistFile)shortcut; if (!name.EndsWith(".lnk")) { name += ".lnk"; } file.Save(Path.Combine(folderPath, name), false); } return(shortcut); }
private void linkToDesktop(string[] fileList, Point pos, bool selfDroped) { if (selfDroped) { return; } //Знаю знаю, плохо, но не хочу сюрпризов try { foreach (var oldfile in fileList) { string newfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Path.GetFileNameWithoutExtension(oldfile)) + ".lnk"; using (ShellLink shortcut = new ShellLink()) { shortcut.Target = oldfile; shortcut.WorkingDirectory = Path.GetDirectoryName(oldfile); shortcut.Description = Path.GetFileNameWithoutExtension(oldfile); shortcut.DisplayMode = LinkDisplayMode.Normal; shortcut.Save(newfile); } dIconManager.updateIcon(newfile); } } catch (Exception e) { new Thread(new ThreadStart(delegate { MessageBox.Show(e.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error); })).Start(); } }
private static void LaunchShortcut(TvPlayer player, UiBroadcastService service, string arguments) { var shortcutPath = Path.Combine(AppUiConfiguration.Current.Folders.Cache, service.FullServiceName) + ".lnk"; // delete exising shortcut if (File.Exists(shortcutPath)) { File.SetAttributes(shortcutPath, FileAttributes.Normal); File.Delete(shortcutPath); } // if var shortcut = new ShellLink(); shortcut.TargetPath = player.Path; shortcut.Arguments = arguments; shortcut.Description = string.Format(Properties.Texts.ExternalPlayerShortcutDescription, player.Name, service.DisplayName); shortcut.IconLocation = service.Logo.GetLogoIconPath(); shortcutPath = shortcut.CreateShortcut(shortcutPath); var start = new ProcessStartInfo() { UseShellExecute = true, FileName = shortcutPath, ErrorDialog = true, }; using (var process = Process.Start(start)) { // no op } // using process } // LaunchShortcut
public void CocreatableClassesWithImplicitInterfaces() { ShellLink shellLink = new ShellLink(); IPersistFile persistFile = (IPersistFile)shellLink; Assert.NotNull(persistFile); }
public void ShorCutServer() { if (!File.Exists(Path.Combine(Utilities.CurrentFolder, "Service.exe"))) { return; } ShellLink link = new ShellLink(); link.Target = Path.Combine(Utilities.CurrentFolder, "Service.exe"); link.WorkingDirectory = Utilities.CurrentFolder; link.ShortCutFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Service - Restart.lnk"); link.Arguments = "/RESTART"; link.Save(); Console.WriteLine("Create Service Restart.lnk"); link = new ShellLink(); link.Target = Path.Combine(Utilities.CurrentFolder, "Service.exe"); link.WorkingDirectory = Utilities.CurrentFolder; link.ShortCutFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Service - Stop.lnk"); link.Arguments = "/STOP"; link.Save(); Console.WriteLine("Create Service Stop.lnk"); link = new ShellLink(); link.Target = Path.Combine(Utilities.CurrentFolder, "Service.exe"); link.WorkingDirectory = Utilities.CurrentFolder; link.ShortCutFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Stop - All Process.lnk"); link.Arguments = "/ALLSTOP"; link.Save(); Console.WriteLine("Create All Process Stop.lnk"); }
public void MakeDesktopShortcut() { using (ShellLink shortcut = new ShellLink()) { var fi = new FileInfo(Assembly.GetExecutingAssembly().Location); string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); shortcut.Target = fi.FullName; shortcut.Arguments = "-run"; shortcut.WorkingDirectory = RootPath; if (this.LatestManifest != null) { shortcut.Description = this.LatestManifest.title; } else { shortcut.Description = fi.Name + " - run"; } shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; shortcut.IconPath = AppPath + "\\favicon.ico"; var fname = new string(shortcut.Description.Where(ch => !Path.GetInvalidFileNameChars().Contains(ch)).ToArray()); shortcut.Save(desktopPath + "/" + fname + ".lnk"); } }
private static Win32 LnkProgram(string path) { var program = Win32Program(path); try { var link = new ShellLink(); const uint STGM_READ = 0; ((IPersistFile)link).Load(path, STGM_READ); var hwnd = new _RemotableHandle(); link.Resolve(ref hwnd, 0); const int MAX_DESCRIPTION = 150; StringBuilder bufferDescription = new StringBuilder(MAX_DESCRIPTION); String description = String.Empty; try { link.GetDescription(bufferDescription, MAX_DESCRIPTION); } catch (COMException e) { Log.Error($"|Win32.LnkProgram|cannot get description <{path}>. HResult: <{e.HResult}>. Exception: <{e}>."); bufferDescription.Clear(); } description = bufferDescription.ToString(); if (!string.IsNullOrEmpty(description)) { program.Description = description; } else { const int MAX_PATH = 260; StringBuilder bufferPath = new StringBuilder(MAX_PATH); var data = new _WIN32_FIND_DATAW(); const uint SLGP_SHORTPATH = 1; link.GetPath(bufferPath, bufferPath.Capacity, ref data, SLGP_SHORTPATH); var target = bufferPath.ToString(); if (!string.IsNullOrEmpty(target)) { var extension = Extension(target); if (extension == ExeExtension && File.Exists(target)) { var info = FileVersionInfo.GetVersionInfo(target); if (!string.IsNullOrEmpty(info.FileDescription)) { program.Description = info.FileDescription; } } } } return(program); } catch (Exception e) { Log.Exception($"|Win32.LnkProgram|Exception when parsing shortcut <{path}>", e); program.Valid = false; return(program); } }
public string ResolveShortcut(string filename) { ShellLink link = new ShellLink(); ((IPersistFile)link).Load(filename, STGM_READ); // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. // ((IShellLinkW)link).Resolve(hwnd, 0) StringBuilder sbPath = new StringBuilder(MAX_PATH); StringBuilder sbDesc = new StringBuilder(MAX_PATH); StringBuilder sbArgs = new StringBuilder(MAX_PATH); StringBuilder sbWorkDir = new StringBuilder(MAX_PATH); StringBuilder sbIconLocn = new StringBuilder(MAX_PATH); int iIconNum = 0; WIN32_FIND_DATAW data = new WIN32_FIND_DATAW(); ((IShellLinkW)link).GetPath(sbPath, sbPath.Capacity, out data, 0); ((IShellLinkW)link).GetDescription(sbDesc, sbDesc.Capacity); ((IShellLinkW)link).GetArguments(sbArgs, sbDesc.Capacity); ((IShellLinkW)link).GetWorkingDirectory(sbWorkDir, sbWorkDir.Capacity); ((IShellLinkW)link).GetIconLocation(sbIconLocn, sbIconLocn.Capacity, out iIconNum); return(sbPath.ToString()); }
private static string ResolveFromShellLinkFile(string filename) { var shellLink = new ShellLink(filename); if (shellLink.Arguments.StartsWith(SteamAppResolver.SteamUrlPattern)) { var resolver = new SteamAppResolver(); return(resolver.ResolveExeFromSteamUrl(shellLink.Arguments)); } var targetInfo = new FileInfo(shellLink.Target); if (targetInfo.Name.ToLower() == SteamAppResolver.SteamExeName) { if (shellLink.Arguments.Contains(SteamAppResolver.SteamArgumentPattern)) { var resolver = new SteamAppResolver(); return(resolver.ResolveExeFromSteamArguments(shellLink.Arguments)); } } if (targetInfo.Extension.ToLower().Equals(".exe")) { return(targetInfo.Name); } return(""); }
public LinkData(string filename, System.Windows.Forms.Form f) { shortcutFile_ = filename; link_ = new ShellLink(); ((IPersistFile)link_).Load(filename, STGM_READ); ((IShellLinkW)link_).Resolve(f.Handle, 0); }
// Retrieve the target path using Shell Link public string retrieveTargetPath(string path) { var link = new ShellLink(); const int STGM_READ = 0; ((IPersistFile)link).Load(path, STGM_READ); var hwnd = new _RemotableHandle(); ((IShellLinkW)link).Resolve(ref hwnd, 0); const int MAX_PATH = 260; StringBuilder buffer = new StringBuilder(MAX_PATH); var data = new WIN32_FIND_DATAW(); ((IShellLinkW)link).GetPath(buffer, buffer.Capacity, ref data, SLGP_FLAGS.SLGP_SHORTPATH); var target = buffer.ToString(); // To set the app description if (!String.IsNullOrEmpty(target)) { buffer = new StringBuilder(MAX_PATH); ((IShellLinkW)link).GetDescription(buffer, MAX_PATH); description = buffer.ToString(); } // To release unmanaged memory Marshal.ReleaseComObject(link); return(target); }
private void BrowseFile() { using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Filter = this.FileFilter; //取消获取lnk目标路径,可选中UWP快捷方式 dlg.DereferenceLinks = false; if (dlg.ShowDialog() == DialogResult.OK) { ItemFilePath = dlg.FileName; string extension = Path.GetExtension(dlg.FileName).ToLower(); if (extension == ".lnk") { using (ShellLink shortcut = new ShellLink(dlg.FileName)) { if (File.Exists(shortcut.TargetPath)) { ItemFilePath = shortcut.TargetPath; Arguments = shortcut.Arguments; } } } ItemText = Path.GetFileNameWithoutExtension(dlg.FileName); } } }
private void CreateLink_Click(object sender, RoutedEventArgs e) { try { var gameInfo = this.allGameInfo.Selected; if (gameInfo == null) { MessageBox.Show("No game selected.", "Blizzbar", MessageBoxButton.OK, MessageBoxImage.Error); return; } var linkFolderPath = this.LinkFolderPath.Text.Trim(); if (linkFolderPath.Length == 0) { MessageBox.Show("No link path set.", "Blizzbar", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (!Directory.Exists(linkFolderPath)) { if (MessageBox.Show("Target directory does not exist. Create it?", "Blizzbar", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.No) { return; } Directory.CreateDirectory(linkFolderPath); } var gameExePath = this.GameExePath.Text.Trim(); if (gameExePath.Length == 0) { if (MessageBox.Show("No game executable selected. This will create a link with no icon. Is this okay?", "Blizzbar", MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes) { return; } } var link = new ShellLink(); var shellLink = (IShellLinkW)link; shellLink.SetPath(@"C:\Windows\Explorer.exe"); shellLink.SetArguments("battlenet://" + gameInfo.UrlName); if (gameExePath.Length > 0) { shellLink.SetIconLocation(gameExePath, 0); } shellLink.SetDescription(gameInfo.FullName); var propStore = (IPropertyStore)link; propStore.SetValue(ref PropertyKey.PKEY_AppUserModel_ID, gameInfo.AppUserModelId); propStore.Commit(); var persistFile = (IPersistFile)link; persistFile.Save(Path.Combine(linkFolderPath, gameInfo.FullName + ".lnk"), true); } catch (Exception ex) { MessageBox.Show("Unable to create link. Reason:\n" + ex.Message, "Blizzbar", MessageBoxButton.OK, MessageBoxImage.Error); } }
private string ResolveLnk(string filename) { var link = new ShellLink(); ((IPersistFile)link).Load(filename, NativeMethods.STGM_READ); // ((IShellLinkW)link).Resolve(hwnd, 0) var sb = new StringBuilder(NativeMethods.MAX_PATH); WIN32_FIND_DATA data; ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0); return sb.ToString(); }
private string ResolveLnk(string filename) { var link = new ShellLink(); ((IPersistFile)link).Load(filename, NativeMethods.STGM_READ); // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. // ((IShellLinkW)link).Resolve(hwnd, 0) var sb = new StringBuilder(NativeMethods.MAX_PATH); WIN32_FIND_DATA data; ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0); return sb.ToString(); }
public void SetAppIdOnShortcutTest() { var sl = new ShellLink() { Target = @"C:\Windows\Notepad.exe", Description = "It's Notepad", }; sl.SetAppUserModelId("org.paulbetts.test"); var path = Path.GetFullPath(@".\test.lnk"); sl.Save(path); Console.WriteLine("Saved to " + path); }
public static string Resolve(string filename) { #if !__MonoCS__ ShellLink link = new ShellLink(); ((IPersistFile)link).Load(filename, STGM_READ); // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. // ((IShellLinkW)link).Resolve(hwnd, 0) StringBuilder sb = new StringBuilder(MAX_PATH); WIN32_FIND_DATAW data = new WIN32_FIND_DATAW(); ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0); return sb.ToString(); #else if (!SIL.IO.RobustFile.Exists(filename)) return string.Empty; return SIL.IO.RobustFile.ReadAllText(filename); #endif }
string installAppVersion(IAppSetup app, Version newCurrentVersion, IEnumerable<ShortcutCreationRequest> shortcutRequestsToIgnore, bool isFirstInstall) { try { if (isFirstInstall) { log.Info("installAppVersion: Doing first install for {0}", app.Target); app.OnAppInstall(); } log.Info("installAppVersion: Doing install for version {0} {1}", newCurrentVersion, app.Target); app.OnVersionInstalled(newCurrentVersion); } catch (Exception ex) { log.ErrorException("App threw exception on install: " + app.GetType().FullName, ex); throw; } var shortcutList = Enumerable.Empty<ShortcutCreationRequest>(); try { shortcutList = app.GetAppShortcutList(); shortcutList.ForEach(x => log.Info("installAppVersion: we have a shortcut {0}", x.TargetPath)); } catch (Exception ex) { log.ErrorException("App threw exception on shortcut uninstall: " + app.GetType().FullName, ex); throw; } shortcutList .Where(x => !shortcutRequestsToIgnore.Contains(x)) .ForEach(x => { var shortcut = x.GetLinkTarget(applicationName, true); var fi = fileSystem.GetFileInfo(shortcut); log.Info("installAppVersion: checking shortcut {0}", fi.FullName); if (fi.Exists) { log.Info("installAppVersion: deleting existing file"); fi.Delete(); } fileSystem.CreateDirectoryRecursive(fi.Directory.FullName); var sl = new ShellLink { Target = x.TargetPath, IconPath = x.IconLibrary, IconIndex = x.IconIndex, Arguments = x.Arguments, WorkingDirectory = x.WorkingDirectory, Description = x.Description, }; sl.Save(shortcut); }); return app.LaunchOnSetup ? app.Target : null; }
public IList<ShellLink> GetShortcutsForExecutable(string exeName, ShortcutLocation locations, bool updateOnly) { this.Log().Info("About to get all shortcuts for {0}, rootAppDir {1}", exeName, rootAppDirectory); var releases = Utility.LoadLocalReleases(Utility.LocalReleaseFileForAppDir(rootAppDirectory)); var thisRelease = Utility.FindCurrentVersion(releases); var updateExe = Path.Combine(rootAppDirectory, "update.exe"); var zf = new ZipPackage(Path.Combine( Utility.PackageDirectoryForAppDir(rootAppDirectory), thisRelease.Filename)); var exePath = Path.Combine(Utility.AppDirForRelease(rootAppDirectory, thisRelease), exeName); var fileVerInfo = FileVersionInfo.GetVersionInfo(exePath); var links = new List<ShellLink>(); foreach (var f in (ShortcutLocation[])Enum.GetValues(typeof(ShortcutLocation))) { if (!locations.HasFlag(f)) continue; var file = linkTargetForVersionInfo(f, zf, fileVerInfo); var fileExists = File.Exists(file); // NB: If we've already installed the app, but the shortcut // is no longer there, we have to assume that the user didn't // want it there and explicitly deleted it, so we shouldn't // annoy them by recreating it. if (!fileExists && updateOnly) { this.Log().Warn("Tried to get shortcut {0} but it appears user deleted it", file); continue; } this.Log().Info("Getting shortcut for {0} => {1}", exeName, file); this.ErrorIfThrows(() => { File.Delete(file); var sl = new ShellLink { Target = updateExe, IconPath = exePath, IconIndex = 0, WorkingDirectory = Path.GetDirectoryName(exePath), Description = zf.Description, Arguments = "--processStart " + exeName, ShortCutFile = "" }; sl.SetAppUserModelId(String.Format("com.squirrel.{0}.{1}", zf.Id, exeName.Replace(".exe", ""))); links.Add(sl); }, "Can't write shortcut: " + file); } return links; }
public static string ResolveShortcut(string filename) { ShellLink link = new ShellLink(); ((IPersistFile)link).Load(filename, STGM_READ); // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. // ((IShellLinkW)link).Resolve(hwnd, 0) StringBuilder sb = new StringBuilder(MAX_PATH); WIN32_FIND_DATAW data = new WIN32_FIND_DATAW(); ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0); return sb.ToString(); }
void ShellTree_NodeClick(object sender, WIN.Forms.TreeNodeMouseClickEventArgs e) { if (e.Button == WIN.Forms.MouseButtons.Middle) { var item = e.Node?.Tag as IListItemEx; if ((item?.IsLink).Value) { var shellLink = new ShellLink(item.ParsingName); item = FileSystemListItem.ToFileSystemItem(this._ShellListView.LVHandle, shellLink.TargetPIDL); shellLink.Dispose(); } if (item != null) tcMain.NewTab(item, false); } }
private static Win32 LnkProgram(string path) { var program = Win32Program(path); try { var link = new ShellLink(); const uint STGM_READ = 0; ((IPersistFile) link).Load(path, STGM_READ); var hwnd = new _RemotableHandle(); link.Resolve(ref hwnd, 0); const int MAX_PATH = 260; StringBuilder buffer = new StringBuilder(MAX_PATH); var data = new _WIN32_FIND_DATAW(); const uint SLGP_SHORTPATH = 1; link.GetPath(buffer, buffer.Capacity, ref data, SLGP_SHORTPATH); var target = buffer.ToString(); if (!string.IsNullOrEmpty(target)) { var extension = Extension(target); if (extension == ExeExtension && File.Exists(target)) { buffer = new StringBuilder(MAX_PATH); link.GetDescription(buffer, MAX_PATH); var description = buffer.ToString(); if (!string.IsNullOrEmpty(description)) { program.Description = description; } else { var info = FileVersionInfo.GetVersionInfo(target); if (!string.IsNullOrEmpty(info.FileDescription)) { program.Description = info.FileDescription; } } } } return program; } catch (COMException e) { // C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\MiracastView.lnk always cause exception Log.Error($"COMException when parsing shortcut: {path}, HResult: {e.HResult}"); Log.Exception(e); program.Valid = false; return program; } catch (Exception e) { Log.Error($"Error when parsing shortcut: {path}"); Log.Exception(e); program.Valid = false; return program; } }
private void mnuPinToStart_Click(object sender, RoutedEventArgs e) { if (_ShellListView.GetSelectedCount() == 1) { string loc = KnownFolders.StartMenu.ParsingName + @"\" + _ShellListView.GetFirstSelectedItem().DisplayName + ".lnk"; var link = new ShellLink(); link.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; link.Target = _ShellListView.GetFirstSelectedItem().ParsingName; link.Save(loc); link.Dispose(); User32.PinUnpinToStartMenu(loc); } if (_ShellListView.GetSelectedCount() == 0) { string loc = KnownFolders.StartMenu.ParsingName + @"\" + _ShellListView.CurrentFolder.DisplayName + ".lnk"; ShellLink link = new ShellLink(); link.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; link.Target = _ShellListView.CurrentFolder.ParsingName; link.Save(loc); link.Dispose(); User32.PinUnpinToStartMenu(loc); } }
public static IntPtr getLinkLocation(string path, Boolean resolve) { using (ShellLink link = new ShellLink()) { link.Load(path); if (resolve) { link.Resolve(); } return link.GetIDList(); } }
private void btnPasetShC_Click(object sender, RoutedEventArgs e) { string PathForDrop = _ShellListView.CurrentFolder.ParsingName; foreach (string item in Clipboards.GetFileDropList()) { using (var shortcut = new ShellLink()) { var o = new ShellItem(item); shortcut.Target = item; shortcut.WorkingDirectory = Path.GetDirectoryName(item); shortcut.Description = o.GetDisplayName(SIGDN.NORMALDISPLAY); shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; shortcut.Save($"{PathForDrop}\\{o.GetDisplayName(SIGDN.NORMALDISPLAY)}.lnk"); AddToLog($"Shortcut created at {PathForDrop}\\{o.GetDisplayName(SIGDN.NORMALDISPLAY)} from source {item}"); } } }
private void btnFavorites_Click(object sender, RoutedEventArgs e) { var selectedItems = _ShellListView.SelectedItems; if (selectedItems.Count == 1) { var link = new ShellLink(); link.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; link.Target = _ShellListView.GetFirstSelectedItem().ParsingName; link.Save($@"{KnownFolders.Links.ParsingName}\{_ShellListView.GetFirstSelectedItem().DisplayName}.lnk"); link.Dispose(); } if (selectedItems.Count == 0) { var link = new ShellLink(); link.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; link.Target = _ShellListView.CurrentFolder.ParsingName; link.Save($@"{KnownFolders.Links.ParsingName}\{_ShellListView.CurrentFolder.DisplayName}.lnk"); link.Dispose(); } }
void updateLink(ShellLink shortcut, string[] oldAppDirectories, string newAppPath) { this.Log().Info("Processing shortcut '{0}'", shortcut.Target); foreach (var oldAppDirectory in oldAppDirectories) { if (!shortcut.Target.StartsWith(oldAppDirectory, StringComparison.OrdinalIgnoreCase) && !shortcut.IconPath.StartsWith(oldAppDirectory, StringComparison.OrdinalIgnoreCase)) { this.Log().Info("Does not match '{0}', continuing to next directory", oldAppDirectory); continue; } // replace old app path with new app path and check, if executable still exists var newTarget = Path.Combine(newAppPath, shortcut.Target.Substring(oldAppDirectory.Length + 1)); if (File.Exists(newTarget)) { shortcut.Target = newTarget; // replace working directory too if appropriate if (shortcut.WorkingDirectory.StartsWith(oldAppDirectory, StringComparison.OrdinalIgnoreCase)) { this.Log().Info("Changing new directory to '{0}'", newAppPath); shortcut.WorkingDirectory = Path.Combine(newAppPath, shortcut.WorkingDirectory.Substring(oldAppDirectory.Length + 1)); } // replace working directory too if appropriate if (shortcut.IconPath.StartsWith(oldAppDirectory, StringComparison.OrdinalIgnoreCase)) { this.Log().Info("Changing new directory to '{0}'", newAppPath); shortcut.IconPath = Path.Combine(newAppPath, shortcut.IconPath.Substring(oldAppDirectory.Length + 1)); } shortcut.Save(); } else { this.Log().Info("Unpinning {0} from taskbar", shortcut.Target); TaskbarHelper.UnpinFromTaskbar(shortcut.Target); } break; } }
/// <summary> /// Converts a managed shell link structure to a COM object. /// </summary> private static IShellLinkW ConvertShellLink(ShellLink shellLink) { var nativeShellLink = (IShellLinkW)new CShellLink(); var nativePropertyStore = (IPropertyStore)nativeShellLink; nativeShellLink.SetPath(shellLink.Path); if (!string.IsNullOrEmpty(shellLink.Arguments)) nativeShellLink.SetArguments(shellLink.Arguments); if (!string.IsNullOrEmpty(shellLink.IconPath)) nativeShellLink.SetIconLocation(shellLink.IconPath, shellLink.IconIndex); nativeShellLink.SetShowCmd(1); // Normal window state SetPropertyValue(nativePropertyStore, new PropertyKey(new Guid("{F29F85E0-4FF9-1068-AB91-08002B27B3D9}"), 2), shellLink.Title); nativePropertyStore.Commit(); return nativeShellLink; }
/// <summary> /// Resolves a shell shortcut's target path /// </summary> /// <param name="filename"></param> /// <returns></returns> public static string ResolveShortcut(string filename) { ShellLink link = new ShellLink(); ((IPersistFile)link).Load(filename, STGM_READ); StringBuilder sb = new StringBuilder(MAX_PATH); WIN32_FIND_DATAW data = new WIN32_FIND_DATAW(); ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0); return sb.ToString(); }
void mif_Click(object sender, RoutedEventArgs e) { using (var obj = (sender as MenuItem).Tag as ShellItem) using (var lnk = new ShellLink(obj.ParsingName)) { NavigationController(FileSystemListItem.ToFileSystemItem(this._ShellListView.LVHandle, lnk.TargetPIDL)); } }
private void ShellTreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e) { if (e.Action == TreeViewAction.Collapse) this._AcceptSelection = false; if (e.Action == TreeViewAction.Expand) { this._ResetEvent.Set(); if (e.Node.Nodes.Count > 0 && (e.Node.Nodes[0].Text == this._EmptyItemString || e.Node.Nodes[0].Text == this._SearchingForFolders)) { e.Node.Nodes.Clear(); imagesQueue.Clear(); childsQueue.Clear(); var sho = e.Node.Tag as IListItemEx; //var lvSho = this.ShellListView != null && this.ShellListView.CurrentFolder != null ? this.ShellListView.CurrentFolder.Clone() : null; var lvSho = this.ShellListView?.CurrentFolder?.Clone(); var node = e.Node; node.Nodes.Add(this._SearchingForFolders); new Thread(() => { var nodesTemp = new List<TreeNode>(); if (sho?.IsLink == true) { try { var shellLink = new ShellLink(sho.ParsingName); var linkTarget = shellLink.TargetPIDL; sho = FileSystemListItem.ToFileSystemItem(IntPtr.Zero, linkTarget); shellLink.Dispose(); } catch { } } foreach (var item in sho?.Where(w => !sho.IsFileSystem && Path.GetExtension(sho?.ParsingName).ToLowerInvariant() != ".library-ms" || ((w.IsFolder || w.IsLink) && (this.IsShowHiddenItems || w.IsHidden == false)))) { if (item?.IsLink == true) { try { var shellLink = new ShellLink(item.ParsingName); var linkTarget = shellLink.TargetPIDL; var itemLinkReal = FileSystemListItem.ToFileSystemItem(IntPtr.Zero, linkTarget); shellLink.Dispose(); if (!itemLinkReal.IsFolder) continue; } catch { } } var itemNode = new TreeNode(item.DisplayName); //IListItemEx itemReal = null; //if (item.Parent?.Parent != null && item.Parent.Parent.ParsingName == KnownFolders.Libraries.ParsingName) { IListItemEx itemReal = item?.Parent?.Parent?.ParsingName == KnownFolders.Libraries.ParsingName ? FileSystemListItem.ToFileSystemItem(IntPtr.Zero, item.ParsingName.ToShellParsingName()) : item; itemNode.Tag = itemReal; if ((sho.IsNetworkPath || sho.IsNetworkPath) && sho.ParsingName != KnownFolders.Network.ParsingName) { itemNode.ImageIndex = this.folderImageListIndex; } else if (itemReal.IconType == IExtractIconPWFlags.GIL_PERCLASS || sho.ParsingName == KnownFolders.Network.ParsingName) { itemNode.ImageIndex = itemReal.GetSystemImageListIndex(itemReal.PIDL, ShellIconType.SmallIcon, ShellIconFlags.OpenIcon); itemNode.SelectedImageIndex = itemNode.ImageIndex; } else { itemNode.ImageIndex = this.folderImageListIndex; } itemNode.Nodes.Add(this._EmptyItemString); if (item.ParsingName.EndsWith(".library-ms")) { var library = ShellLibrary.Load(Path.GetFileNameWithoutExtension(item.ParsingName), false); if (library.IsPinnedToNavigationPane) nodesTemp.Add(itemNode); library.Close(); } else { nodesTemp.Add(itemNode); } //Application.DoEvents(); } this.BeginInvoke((Action)(() => { if (node.Nodes.Count == 1 && node.Nodes[0].Text == _SearchingForFolders) node.Nodes.RemoveAt(0); node.Nodes.AddRange(nodesTemp.ToArray()); if (lvSho != null) this.SelItem(lvSho); })); }).Start(); } } }
/// <summary> /// Creates a shortcut file pointing to a specified path /// </summary> /// <param name="shortcutPath">The shortcut path.</param> /// <param name="target">The target.</param> /// <exception cref="System.ArgumentNullException">shortcutPath</exception> public static void CreateShortcut(string shortcutPath, string target) { if (string.IsNullOrEmpty(shortcutPath)) { throw new ArgumentNullException("shortcutPath"); } if (string.IsNullOrEmpty(target)) { throw new ArgumentNullException("target"); } var link = new ShellLink(); ((IShellLinkW)link).SetPath(target); ((IPersistFile)link).Save(shortcutPath, true); }
/// <summary> /// Resolves the shortcut. /// </summary> /// <param name="filename">The filename.</param> /// <returns>System.String.</returns> /// <exception cref="System.ArgumentNullException">filename</exception> public static string ResolveShortcut(string filename) { if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); } var link = new ShellLink(); ((IPersistFile)link).Load(filename, NativeMethods.STGM_READ); // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. // ((IShellLinkW)link).Resolve(hwnd, 0) var sb = new StringBuilder(NativeMethods.MAX_PATH); WIN32_FIND_DATA data; ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0); return sb.ToString(); }
public bool ResolveShortcut(string shortcut, out string filepath, out string arguments) { ShellLink link = new ShellLink(); ((IPersistFile)link).Load(shortcut, STGM_READ); // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. // ((IShellLinkW)link).Resolve(hwnd, 0) StringBuilder path = new StringBuilder(MAX_PATH); WIN32_FIND_DATAW data = new WIN32_FIND_DATAW(); ((IShellLinkW)link).GetPath(path, path.Capacity, out data, 0); StringBuilder args = new StringBuilder(MAX_PATH); ((IShellLinkW)link).GetArguments(args, args.Capacity); filepath = path.ToString(); arguments = args.ToString(); if (!File.Exists(filepath)) return false; return true; }
public void CreateShortcutsForExecutable(string exeName, ShortcutLocation locations, bool updateOnly, string programArguments, string icon) { this.Log().Info("About to create shortcuts for {0}, rootAppDir {1}", exeName, rootAppDirectory); var releases = Utility.LoadLocalReleases(Utility.LocalReleaseFileForAppDir(rootAppDirectory)); var thisRelease = Utility.FindCurrentVersion(releases); var updateExe = Path.Combine(rootAppDirectory, "update.exe"); var zf = new ZipPackage(Path.Combine( Utility.PackageDirectoryForAppDir(rootAppDirectory), thisRelease.Filename)); var exePath = Path.Combine(Utility.AppDirForRelease(rootAppDirectory, thisRelease), exeName); var fileVerInfo = FileVersionInfo.GetVersionInfo(exePath); foreach (var f in (ShortcutLocation[]) Enum.GetValues(typeof(ShortcutLocation))) { if (!locations.HasFlag(f)) continue; var file = linkTargetForVersionInfo(f, zf, fileVerInfo); var fileExists = File.Exists(file); // NB: If we've already installed the app, but the shortcut // is no longer there, we have to assume that the user didn't // want it there and explicitly deleted it, so we shouldn't // annoy them by recreating it. if (!fileExists && updateOnly) { this.Log().Warn("Wanted to update shortcut {0} but it appears user deleted it", file); continue; } this.Log().Info("Creating shortcut for {0} => {1}", exeName, file); ShellLink sl; this.ErrorIfThrows(() => Utility.Retry(() => { File.Delete(file); sl = new ShellLink { Target = updateExe, IconPath = icon ?? exePath, IconIndex = 0, WorkingDirectory = Path.GetDirectoryName(exePath), Description = zf.Description, Arguments = "--processStart \"" + exeName + "\"", }; if (!String.IsNullOrWhiteSpace(programArguments)) { sl.Arguments += String.Format(" -a \"{0}\"", programArguments); } sl.SetAppUserModelId(String.Format("com.squirrel.{0}.{1}", zf.Id.Replace(" ", ""), exeName.Replace(".exe", "").Replace(" ", ""))); this.Log().Info("About to save shortcut: {0} (target {1}, workingDir {2}, args {3})", file, sl.Target, sl.WorkingDirectory, sl.Arguments); if (ModeDetector.InUnitTestRunner() == false) sl.Save(file); }, 4), "Can't write shortcut: " + file); } fixPinnedExecutables(zf.Version); }
public static string getLinkLocation(string path ) { using (ShellLink link = new ShellLink()) { link.Load(path); return link.GetPath(); } }
private void ShellTreeView_AfterSelect(object sender, TreeViewEventArgs e) { if (!this._AcceptSelection) { this._AcceptSelection = true; return; } //var sho = e.Node != null ? e.Node.Tag as IListItemEx : null; var sho = e?.Node?.Tag as IListItemEx; if (sho != null) { IListItemEx linkSho = null; if (sho.IsLink) { try { var shellLink = new ShellLink(sho.ParsingName); var linkTarget = shellLink.TargetPIDL; linkSho = FileSystemListItem.ToFileSystemItem(IntPtr.Zero, linkTarget); shellLink.Dispose(); } catch { } } this.isFromTreeview = true; if (this._IsNavigate) { this.ShellListView.Navigate_Full(linkSho ?? sho, true, true); } this._IsNavigate = false; this.isFromTreeview = false; } }
private static Win32 LnkProgram(string path) { var program = Win32Program(path); try { var link = new ShellLink(); const uint STGM_READ = 0; ((IPersistFile)link).Load(path, STGM_READ); var hwnd = new _RemotableHandle(); link.Resolve(ref hwnd, 0); const int MAX_PATH = 260; StringBuilder buffer = new StringBuilder(MAX_PATH); var data = new _WIN32_FIND_DATAW(); const uint SLGP_SHORTPATH = 1; link.GetPath(buffer, buffer.Capacity, ref data, SLGP_SHORTPATH); var target = buffer.ToString(); var extension = Extension(target); if (!string.IsNullOrEmpty(target) && (extension == ExeExtension)) { buffer = new StringBuilder(MAX_PATH); link.GetDescription(buffer, MAX_PATH); var description = buffer.ToString(); if (!string.IsNullOrEmpty(description)) { program.Description = description; } else { var info = FileVersionInfo.GetVersionInfo(target); if (!string.IsNullOrEmpty(info.FileDescription)) { program.Description = info.FileDescription; } } } return program; } catch (Exception) { Log.Error($"Error when parsing shortcut: {path}"); return program; } }
public Dictionary<ShortcutLocation, ShellLink> GetShortcutsForExecutable(string exeName, ShortcutLocation locations, string programArguments) { this.Log().Info("About to create shortcuts for {0}, rootAppDir {1}", exeName, rootAppDirectory); var releases = Utility.LoadLocalReleases(Utility.LocalReleaseFileForAppDir(rootAppDirectory)); var thisRelease = Utility.FindCurrentVersion(releases); var updateExe = Path.Combine(rootAppDirectory, "update.exe"); var zf = new ZipPackage(Path.Combine( Utility.PackageDirectoryForAppDir(rootAppDirectory), thisRelease.Filename)); var exePath = Path.Combine(Utility.AppDirForRelease(rootAppDirectory, thisRelease), exeName); var fileVerInfo = FileVersionInfo.GetVersionInfo(exePath); var ret = new Dictionary<ShortcutLocation, ShellLink>(); foreach (var f in (ShortcutLocation[]) Enum.GetValues(typeof(ShortcutLocation))) { if (!locations.HasFlag(f)) continue; var file = linkTargetForVersionInfo(f, zf, fileVerInfo); this.Log().Info("Creating shortcut for {0} => {1}", exeName, file); ShellLink sl; sl = new ShellLink { Target = updateExe, IconPath = exePath, IconIndex = 0, WorkingDirectory = Path.GetDirectoryName(exePath), Description = zf.Description, Arguments = "--processStart \"" + exeName + "\"", }; if (!String.IsNullOrWhiteSpace(programArguments)) { sl.Arguments += String.Format(" -a \"{0}\"", programArguments); } sl.SetAppUserModelId(String.Format("com.squirrel.{0}.{1}", zf.Id.Replace(" ", ""), exeName.Replace(".exe", "").Replace(" ", ""))); ret.Add(f, sl); } return ret; }
public static void ResolveShortcut(string filename, out string name, out string command, out string args, out string description, out string iconLocation, out int iconIndex) { ShellLink link = new ShellLink(); ((IPersistFile)link).Load(filename, STGM_READ); // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. //((IShellLinkW)link).Resolve(IntPtr.Zero, SLR_FLAGS.SLR_ANY_MATCH); StringBuilder sb = new StringBuilder(MAX_PATH); WIN32_FIND_DATAW data = new WIN32_FIND_DATAW(); ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, SLGP_FLAGS.SLGP_RAWPATH); command = sb.ToString(); sb = new StringBuilder(MAX_PATH); //MAX_PATH? ((IShellLinkW)link).GetArguments(sb, sb.Capacity); args = sb.ToString(); description = ""; try { sb = new StringBuilder(MAX_PATH); //MAX_PATH? ((IShellLinkW)link).GetDescription(sb, sb.Capacity); description = sb.ToString(); } catch (COMException ex) { } sb = new StringBuilder(MAX_PATH); //MAX_PATH? var hresult = ((IShellLinkW)link).GetIconLocation(sb, sb.Capacity, out iconIndex); iconLocation = sb.ToString(); if (hresult != 0) { CoreLib.Log("GetIconLocation result: " + hresult); } name = GetLocalizedName.GetName(filename); }
void updateLink(ShellLink shortcut, string newAppPath) { this.Log().Info("Processing shortcut '{0}'", shortcut.ShortCutFile); var target = Environment.ExpandEnvironmentVariables(shortcut.Target); var targetIsUpdateDotExe = target.EndsWith("update.exe", StringComparison.OrdinalIgnoreCase); this.Log().Info("Old shortcut target: '{0}'", target); if (!targetIsUpdateDotExe) { target = Path.Combine(newAppPath, Path.GetFileName(shortcut.Target)); } this.Log().Info("New shortcut target: '{0}'", target); shortcut.WorkingDirectory = newAppPath; shortcut.Target = target; // NB: If the executable was in a previous version but not in this // one, we should disappear this pin. if (!File.Exists(target)) { shortcut.Dispose(); this.ErrorIfThrows(() => Utility.DeleteFileHarder(target), "Failed to delete outdated pinned shortcut to: " + target); return; } this.Log().Info("Old iconPath is: '{0}'", shortcut.IconPath); if (!File.Exists(shortcut.IconPath) || shortcut.IconPath.IndexOf("app-", StringComparison.OrdinalIgnoreCase) > 1) { var iconPath = Path.Combine(newAppPath, Path.GetFileName(shortcut.IconPath)); if (!File.Exists(iconPath) && targetIsUpdateDotExe) { var executable = shortcut.Arguments.Replace("--processStart ", ""); iconPath = Path.Combine(newAppPath, executable); } this.Log().Info("Setting iconPath to: '{0}'", iconPath); shortcut.IconPath = iconPath; if (!File.Exists(iconPath)) { this.Log().Warn("Tried to use {0} for icon path but didn't exist, falling back to EXE", iconPath); shortcut.IconPath = target; shortcut.IconIndex = 0; } } this.ErrorIfThrows(() => Utility.Retry(() => shortcut.Save(), 2), "Couldn't write shortcut " + shortcut.ShortCutFile); this.Log().Info("Finished shortcut successfully"); }
public static string ResolveShortcut(string filename) { var link = new ShellLink(); ((IPersistFile)link).Load(filename, StgmRead); // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. // ((IShellLinkW)link).Resolve(hwnd, 0) StringBuilder sb = new StringBuilder(MaxPath); Win32FindDataw data; new Win32FindDataw(); ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0); return sb.ToString(); }