private void saveShortcutAs()
        {
            SaveFileDialog s = new SaveFileDialog();

            s.Filter          = "Shortcut Files (*.lnk)|*.lnk|All Files (*.*)|*.*";
            s.FilterIndex     = 1;
            s.DefaultExt      = "LNK";
            s.CheckPathExists = true;
            if (s.ShowDialog(this) == DialogResult.OK)
            {
                // set path to save to
                link.ShortCutFile = s.FileName;

                // set the details of the link:
                link.Target      = txtTarget.Text;
                link.Arguments   = txtArguments.Text;
                link.Description = txtDescription.Text;
                link.IconPath    = txtIconFile.Text;
                link.IconIndex   = (txtIconIndex.Text.Length > 0 ?
                                    System.Int32.Parse(txtIconIndex.Text) : 0);

                // save the link:
                link.Save();

                // refresh details:
                showDetails();
            }
        }
Esempio n. 2
0
        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");
            }
        }
Esempio n. 3
0
 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(); }
 }
Esempio n. 4
0
        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));
        }
Esempio n. 5
0
        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
            {};
        }
Esempio n. 6
0
        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();
        }
Esempio n. 7
0
        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;
        }
Esempio n. 8
0
        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);
                }
            };
        }
Esempio n. 9
0
        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);
                }
            }
        }
Esempio n. 10
0
        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");
        }
Esempio n. 11
0
        public TrueCryptSWObj(ProgramData thisProg) // initialize all static entries
        {

            tCryptRegEntry = (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Classes\TrueCryptVolume\Shell\open\command", "", "");
            if (tCryptRegEntry != null)
            {
                tcProgramFQN = tCryptRegEntry.Substring(1, tCryptRegEntry.Length - 10); //registry entry has a leading quote that needs to go
                tcProgramDirectory = tcProgramFQN.Substring(0, tcProgramFQN.Length - 14);
                if (!File.Exists(tcProgramFQN))
                {
                    MessageBox.Show("Windows has registry entries for the TrueCrypt Program but no program exists. Please reinstall", thisProg.mbCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Environment.Exit(1);
                }
                if (thisProg.removable == true && string.Compare(FileVersionInfo.GetVersionInfo(tcProgramFQN).FileVersion, tcSetupVersion) < 0)
                {   // we have host version that needs upgrading
                    MessageBox.Show("The TrueCrypt software version on this Flash Drive will not work with the version of TrueCrypt on this host system. The Tax-Aide TrueCrypt Utility will be started so that the Host's TrueCrypt can be upgraded. Then restart this Start Tax-Aide drive program", thisProg.mbCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    try
                    {
                        Process proc = Process.Start(thisProg.drvLetter + ":\\" + travDir + TAtcSetupProgramName, "hostupg");
                        Environment.Exit(1);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Exception on starting Tax-Aide TrueCrypt Utility\r\n" + e.ToString(), thisProg.mbCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                if (thisProg.removable == true)
                {
                    tcProgramFQN = thisProg.drvLetter + ":\\" + travDir + tcProgramName;
                    tcProgramDirectory = thisProg.drvLetter + ":\\" + travDir;
                    if (!File.Exists(tcProgramFQN))
                    {
                        MessageBox.Show("The TrueCrypt Program does not exist on the Traveler drive. Please reinistall" + "\r" + tcProgramFQN, thisProg.mbCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Environment.Exit(1);
                    }
                }
                else
                {
                    MessageBox.Show("The TrueCrypt program does not exist. Please run the Tax-Aide TrueCrypt Installer", thisProg.mbCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Environment.Exit(1);
                }
            }
#if StartTADrive
            if (thisProg.removable == true)
            {
                //Incase shortcut exists delete it
                File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\Stop Traveler.lnk");
                ShellLink desktopShortcut = new ShellLink();
                desktopShortcut.ShortCutFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\Stop Traveler.lnk";
                desktopShortcut.Target = thisProg.scriptExePath + stopTravDrv;
                desktopShortcut.IconPath = thisProg.scriptExePath + "\\" + "Stop_Tax-Aide_Drive.exe";
                desktopShortcut.Save();
                desktopShortcut.Dispose();
            } 
#endif
        }
Esempio n. 12
0
        private void PinTempShortcutFromHwnd(IntPtr hWnd, string appId)
        {
            if (DisableShortcutChanging)
            {
                return;
            }

            // Get process ID from window
            int hwndPid;

            Interop.GetWindowThreadProcessId(hWnd, out hwndPid);

            // Get process handle from pID; get process path from handle
            IntPtr        hwndPidHandle         = Interop.OpenProcess(Interop.ProcessAccess.QueryInformation | Interop.ProcessAccess.VMRead, false, hwndPid);
            StringBuilder hwndProcessNameString = new StringBuilder(260);

            Interop.GetModuleFileNameEx(hwndPidHandle, IntPtr.Zero, hwndProcessNameString, 260);
            Interop.CloseHandle(hwndPidHandle);

            string hwndProcessPath;

            try { hwndProcessPath = hwndProcessNameString.ToString(); }
            catch (Exception e) { return; }

            if (!File.Exists(hwndProcessPath))
            {
                return;
            }

            string hwndProcessName = Path.GetFileNameWithoutExtension(hwndProcessPath).ToLower();

            if (IsAppPinnedByProcessName(hwndProcessName))
            {
                return;
            }

            string newLnkPath = Path.Combine(Common.Path_AppData, "TempShortcuts" + "\\" + hwndProcessName + ".lnk");

            using (ShellLink shortcut = new ShellLink())
            {
                shortcut.Target           = hwndProcessPath;
                shortcut.WorkingDirectory = Path.GetDirectoryName(hwndProcessPath);
                shortcut.Description      = hwndProcessName;
                shortcut.DisplayMode      = ShellLink.LinkDisplayMode.edmNormal;
                shortcut.Save(newLnkPath);
            }

            Common.TaskbarManagerInstance.SetApplicationIdForShortcut(newLnkPath, appId);

            if (TempShortcut_AppIdPairs.ContainsKey(newLnkPath))
            {
                TempShortcut_AppIdPairs.Remove(newLnkPath);
            }
            TempShortcut_AppIdPairs.Add(newLnkPath, appId);

            PinShortcut(newLnkPath, false);
        }
Esempio n. 13
0
            private void CreateUninstallShortCut(string targetPath)
            {
                bool createShortcuts = Runner.Variables.GetOptional <bool>(
                    Constants.ScriptVariables.CreateShortcuts
                    );

                if (!createShortcuts)
                {
                    return;
                }

                string startMenuPath = Runner.Variables.GetRequired <string>(
                    Constants.ScriptVariables.StartMenuPath
                    );

                string startMenuBase = NativeMethods.SHGetFolderPath(
                    IntPtr.Zero,
                    NativeMethods.SpecialFolderCSIDL.CSIDL_STARTMENU,
                    IntPtr.Zero,
                    0
                    );

                startMenuPath = Path.Combine(startMenuBase, startMenuPath);

                AddToInstallLog(new InstallLogCreateDirectory
                {
                    Path  = startMenuPath,
                    Force = false
                });

                Directory.CreateDirectory(startMenuPath);

                string shortcutFileName = Path.Combine(
                    startMenuPath,
                    UILabels.Uninstall + ".lnk"
                    );

                AddToInstallLog(new InstallLogCreateFile
                {
                    Path = shortcutFileName
                });

                _form.RaiseProgressChanged(String.Format(UILabels.CreatingShortcut, shortcutFileName));

                var shellLink = new ShellLink
                {
                    Target    = Path.Combine(targetPath, Constants.NuGetUpdateFileName),
                    IconIndex = 1,
                    IconPath  = Path.Combine(targetPath, Constants.NuGetUpdateFileName),
                    Arguments = String.Format("-r -p {0}", Escaping.ShellEncode(Runner.Environment.Config.PackageCode))
                };

                shellLink.SetPropertyValue(PropertyStoreProperty.AppUserModel_StartPinOption, 1 /* APPUSERMODEL_STARTPINOPTION_NOPINONINSTALL */);
                shellLink.SetPropertyValue(PropertyStoreProperty.AppUserModel_ExcludeFromShowInNewInstall, true);

                shellLink.Save(shortcutFileName);
            }
Esempio n. 14
0
        public void CreateShortcut(string targetFile, string destinationFile, string description)
        {
            var sl = new ShellLink
            {
                Target      = targetFile,
                Description = description
            };

            sl.Save(destinationFile);
        }
 private void CreateStartShortcut()
 {
     using (var link = new ShellLink())
     {
         link.Target      = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FX.Mobile.DeveloperTools.Launcher.exe");
         link.Description = "Start Mobile Website";
         link.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
         link.Arguments   = "\"/path:" + MobilePath + "\"";
         link.Save(Path.Combine(MobilePath, link.Description + ".lnk"));
     }
 }
Esempio n. 16
0
 private static void CreateLink(string path, string favPath)
 {
     using (ShellLink shortcut = new ShellLink())
     {
         shortcut.Target           = path;
         shortcut.WorkingDirectory = path;
         shortcut.Description      = "Your MEGA backup folder";
         shortcut.DisplayMode      = ShellLink.LinkDisplayMode.edmNormal;
         try { shortcut.Save(favPath); }
         catch { }
     }
 }
Esempio n. 17
0
        public void CreateShortcut(string targetFile, string workingDirectory, string destinationFile,
                                   string description)
        {
            var sl = new ShellLink
            {
                Target           = targetFile,
                Description      = description,
                WorkingDirectory = workingDirectory
            };

            sl.Save(destinationFile);
        }
Esempio n. 18
0
        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);
        }
Esempio n. 19
0
        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);
        }
Esempio n. 20
0
        private static string[] GetSortedPaths(string groupPath, out bool sorted)
        {
            sorted = false;
            List <string> sortedPaths = new List <string>();

            string[] paths = Directory.GetFiles(groupPath, "*.lnk");
            for (int i = paths.Length - 1; i >= 0; i--)
            {
                string srcPath = paths[i];
                string name    = Path.GetFileName(srcPath);
                int    index   = name.IndexOf(" - ");
                if (index >= 2 && int.TryParse(name.Substring(0, index), out int num) && num == i + 1)
                {
                    sortedPaths.Add(srcPath); continue;
                }
                if (index >= 0)
                {
                    name = name.Substring(index + 3);
                }
                string dstPath = $@"{groupPath}\{(i + 1).ToString().PadLeft(2, '0')} - {name}";
                dstPath = ObjectPath.GetNewPathWithIndex(dstPath, ObjectPath.PathType.File);

                string value;
                using (ShellLink srcLnk = new ShellLink(srcPath))
                {
                    value = srcLnk.Description?.Trim();
                }
                if (string.IsNullOrEmpty(value))
                {
                    value = DesktopIni.GetLocalizedFileNames(srcPath);
                }
                if (string.IsNullOrEmpty(value))
                {
                    value = Path.GetFileNameWithoutExtension(name);
                }
                DesktopIni.DeleteLocalizedFileNames(srcPath);
                DesktopIni.SetLocalizedFileNames(dstPath, value);
                File.Move(srcPath, dstPath);
                using (ShellLink dstLnk = new ShellLink(dstPath))
                {
                    dstLnk.Description = value;
                    dstLnk.Save();
                }
                sortedPaths.Add(dstPath);
                sorted = true;
            }
            return(sortedPaths.ToArray());
        }
Esempio n. 21
0
 public bool ChangeCommand(ShellLink shellLink)
 {
     using (CommandDialog dlg = new CommandDialog())
     {
         dlg.Command   = shellLink.TargetPath;
         dlg.Arguments = shellLink.Arguments;
         if (dlg.ShowDialog() != DialogResult.OK)
         {
             return(false);
         }
         shellLink.TargetPath = dlg.Command;
         shellLink.Arguments  = dlg.Arguments;
         shellLink.Save();
         return(true);
     }
 }
        void CreateShortcutFor(string fileName, string description)
        {
            using (ShellLink shortcut = new ShellLink())
            {
                // The file that the .lnk file links to
                string target = //ComponentStorage.GetValue<string>(FrbdkSetupComponent.Path)
                                FrbdkUpdaterManager.FrbdkInProgramFiles
                                + fileName;
                shortcut.Target           = target;
                shortcut.WorkingDirectory = Path.GetDirectoryName(target);
                shortcut.Description      = description;
                shortcut.DisplayMode      = ShellLink.LinkDisplayMode.edmNormal;

                // Where to save the .lnk file
                shortcut.Save(StartMenuFolder + FileManager.RemovePath(FileManager.RemoveExtension(fileName)) + ".lnk");
            }
        }
Esempio n. 23
0
 /// <summary>
 /// Registers the specified assembly to be launched at startup.
 /// </summary>
 /// <param name="assembly">The assembly.</param>
 /// <param name="commandLine">The command line.</param>
 public void RegisterStartup(Assembly assembly, string commandLine = null)
 {
     using (var shortcut = new ShellLink())
     {
         var location = assembly.Location;
         shortcut.Target           = location;
         shortcut.WorkingDirectory = Path.GetDirectoryName(location);
         shortcut.DisplayMode      = ShellLink.LinkDisplayMode.edmNormal;
         shortcut.IconPath         = location;
         shortcut.IconIndex        = 0;
         if (commandLine != null)
         {
             shortcut.Arguments = commandLine;
         }
         shortcut.Save(GetShortcutPath(assembly));
     }
 }
Esempio n. 24
0
        private void CreateShortcut(string shortcutFileName, string mainIcon)
        {
            var shellLink = new ShellLink
            {
                Target           = PackageManager.GetEntryAssemblyLocation(_configuration.InstallationPath),
                WorkingDirectory = _configuration.InstallationPath
            };

            if (mainIcon != null)
            {
                shellLink.IconPath = mainIcon;
            }

            Directory.CreateDirectory(Path.GetDirectoryName(shortcutFileName));

            shellLink.Save(shortcutFileName);
        }
Esempio n. 25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="b2"></param>
        public static void func_新增或刪除開機自動啟動捷徑(bool b2)
        {
            //取得 windows啟動資料夾 的路徑
            String s_啟動資料夾  = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            String s_捷徑儲存路徑 = Path.Combine(s_啟動資料夾, "TeifSee.lnk");

            if (b2)  //啟用「開機自動啟動程式」

            {
                String s_啟動參數 = @"none";

                String s_工作資料夾 = Directory.GetParent(System.AppDomain.CurrentDomain.BaseDirectory).ToString();
                s_工作資料夾 = Directory.GetParent(s_工作資料夾).ToString();
                String s_exe路徑 = Path.Combine(s_工作資料夾, "TiefSee.exe");
                String s_圖示檔案  = s_exe路徑;

                if (File.Exists(s_exe路徑) == false)
                {
                    MessageBox.Show("找不到\n" + s_exe路徑);
                    return;
                }

                //產生捷徑
                ShellLink slLinkObject = new ShellLink();
                slLinkObject.WorkPath         = s_工作資料夾;
                slLinkObject.IconLocation     = s_圖示檔案 + ",0"; // 0 為圖示檔的 Index
                slLinkObject.ExecuteFile      = s_exe路徑;
                slLinkObject.ExecuteArguments = s_啟動參數;
                slLinkObject.Save(s_捷徑儲存路徑);

                slLinkObject.Dispose();
            }
            else    //刪除捷徑

            {
                if (File.Exists(s_捷徑儲存路徑))
                {
                    try {
                        File.Delete(s_捷徑儲存路徑);
                    } catch { }
                }
            }
        }
Esempio n. 26
0
            public override void CreateShortcut(CreateShortcut action)
            {
                string shortcutFileName = Runner.InvokeExpression <string>(
                    action.ShortcutFileName
                    );

                AddToInstallLog(new InstallLogCreateFile
                {
                    Path = shortcutFileName
                });

                _form.RaiseProgressChanged(String.Format(UILabels.CreatingShortcut, shortcutFileName));

                var shellLink = new ShellLink
                {
                    Target = Runner.InvokeExpression <string>(action.TargetFileName),
                };

                if (action.IconFileName != null)
                {
                    shellLink.IconPath = Runner.InvokeExpression <string>(action.IconFileName);
                }

                if (action.IconIndex != null)
                {
                    shellLink.IconIndex = Runner.InvokeExpression <int>(action.IconIndex);
                }

                if (action.StartOptions != null)
                {
                    shellLink.Arguments = Runner.InvokeExpression <string>(action.StartOptions);
                }

                if (action.Description != null)
                {
                    shellLink.Description = Runner.ParseTemplate(action.Description);
                }

                Directory.CreateDirectory(Path.GetDirectoryName(shortcutFileName));

                shellLink.Save(shortcutFileName);
            }
Esempio n. 27
0
 private void CreateShortcut(string shortcutPath,
                             string executablePath,
                             string appUserModelId,
                             string toastActivatorId)
 {
     try
     {
         using (ShellLink shortcut = new ShellLink())
         {
             shortcut.TargetPath       = executablePath;
             shortcut.AppUserModelID   = appUserModelId;
             shortcut.ToastActivatorId = new Guid(toastActivatorId);
             shortcut.Save(shortcutPath);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("Could not created shortcut file. " + ex.Message);
     }
 }
 public Win8Toaster()
 {
     ShortcutLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Microsoft\Windows\Start Menu\Programs\YourCompany\YourApplication.lnk");
     //We need a start menu shortcut (a ShellLink object) to show toasts.
     if (!File.Exists(ShortcutLocation))
     {
         string directory = Path.GetDirectoryName(ShortcutLocation);
         if (!Directory.Exists(directory))
         {
             Directory.CreateDirectory(directory);
         }
         using (ShellLink shortcut = new ShellLink())
         {
             shortcut.TargetPath     = System.Reflection.Assembly.GetEntryAssembly().Location;
             shortcut.Arguments      = "";
             shortcut.AppUserModelID = APPUSERMODELID;
             shortcut.Save(ShortcutLocation);
         }
     }
     ToastNotifier = ToastNotificationManager.CreateToastNotifier(APPUSERMODELID);
 }
Esempio n. 29
0
 private void step5FinishButton_Click(object sender, EventArgs e)
 {
     step5FinishButton.Enabled = false;
     if (metroCheckBox1.Checked)
     {
         using (var shortcut = new ShellLink())
         {
             shortcut.Target           = installedLocation + "\\Shotr.exe";
             shortcut.WorkingDirectory = Path.GetDirectoryName(installedLocation + "\\Shotr.exe");
             shortcut.Description      = "Shotr - Region Capture";
             shortcut.Arguments        = "--region";
             shortcut.IconPath         = Path.GetDirectoryName(installedLocation) + "\\shotr-region.ico";
             shortcut.DisplayMode      = ShellLink.LinkDisplayMode.edmNormal;
             shortcut.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Shotr - Capture.lnk");
         }
         using (var shortcut = new ShellLink())
         {
             shortcut.Target           = installedLocation + "\\Shotr.exe";
             shortcut.WorkingDirectory = Path.GetDirectoryName(installedLocation + "\\Shotr.exe");
             shortcut.Description      = "Shotr - Record";
             shortcut.Arguments        = "--record";
             shortcut.IconPath         = Path.GetDirectoryName(installedLocation) + "\\shotr-record.ico";
             shortcut.DisplayMode      = ShellLink.LinkDisplayMode.edmNormal;
             shortcut.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Shotr - Record.lnk");
         }
     }
     if (step5CheckBox.Checked)
     //start shit.
     {
         if (!WineDetectionService.IsWine())
         {
             RunAsDesktopUser.Run(installedLocation + "\\Shotr.exe");
         }
         else
         {
             Process.Start(installedLocation + "\\Shotr.exe");
         }
     }
     Environment.Exit(0);
 }
            private void UpdateLink(ShellLink shortcut, string newAppPath)
            {
                Log.InfoFormat("Processing shortcut '{0}'", shortcut.ShortCutFile);

                var target = Environment.ExpandEnvironmentVariables(shortcut.Target);
                var targetIsUpdateDotExe = target.EndsWith("update.exe", StringComparison.OrdinalIgnoreCase);

                Log.InfoFormat("Old shortcut target: '{0}'", target);

                // NB: In 1.5.0 we accidentally fixed the target of pinned shortcuts but left the arguments,
                // so if we find a shortcut with --processStart in the args, we're gonna stomp it even though
                // what we _should_ do is stomp it only if the target is Update.exe
                if (shortcut.Arguments.Contains("--processStart"))
                {
                    shortcut.Arguments = "";
                }

                if (!targetIsUpdateDotExe)
                {
                    target = Path.Combine(rootAppDirectory, Path.GetFileName(shortcut.Target));
                }
                else
                {
                    target = Path.Combine(rootAppDirectory, Path.GetFileName(shortcut.IconPath));
                }

                Log.InfoFormat("New shortcut target: '{0}'", target);

                shortcut.WorkingDirectory = newAppPath;
                shortcut.Target           = target;

                Log.InfoFormat("Old iconPath is: '{0}'", shortcut.IconPath);
                shortcut.IconPath  = target;
                shortcut.IconIndex = 0;

                Log.ErrorIfThrows(() => Utility.Retry(() => shortcut.Save()), "Couldn't write shortcut " + shortcut.ShortCutFile);
                Log.InfoFormat("Finished shortcut successfully");
            }
Esempio n. 31
0
        /// <summary>
        /// Creates a shortcut file for the given executable
        /// </summary>
        /// <param name="LinkFullPath">The full path to the file name to be used for the shortcut.  If it does not end with .lnk, then .lnk will be appended.</param>
        /// <param name="LinkDescription">The description for the shortcut.</param>
        /// <param name="DestPath">The full path to the file the shortcut will open.</param>
        /// <param name="DestArguments">Any arguments that will be used when launching the file.</param>
        /// <param name="IconSource">The icon that will be used.  If not provided, the icon will be the default icon for the DestPath.</param>
        /// <param name="IconSourceIndex">The icon index that will be used.  If not provided, the default icon index will be used.</param>
        /// <returns>The created shortcut file</returns>
        public static ShellLink CreateFullPath(string LinkFullPath, string LinkDescription, string DestPath, string DestArguments = DEST_ARGUMENTS_NONE, string IconSource = ICON_FROM_DESTINATION, int IconSourceIndex = ICON_INDEX_DEFAULT)
        {
            LinkFullPath = EnsureLinkName(LinkFullPath);

            var ret = new ShellLink()
            {
                Target           = DestPath,
                IconPath         = IconSource ?? DestPath,
                IconIndex        = IconSourceIndex,
                WorkingDirectory = System.IO.Path.GetDirectoryName(DestPath),
                Description      = LinkDescription
            };

            if (!String.IsNullOrWhiteSpace(DestArguments))
            {
                ret.Arguments = $@" -a ""{DestArguments}""";
            }

            Delete(LinkFullPath);

            ret.Save(LinkFullPath);

            return(ret);
        }
            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;
                }
            }
Esempio n. 33
0
        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;
        }
Esempio n. 34
0
 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}");
     }
   }
 }
            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);
            }
Esempio n. 36
0
    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);
      }
    }
            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");
            }
Esempio n. 38
0
    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();
      }
    }