예제 #1
0
        public static void Initialize()
        {
            using (new Mutex(true, ProcessEx.CurrentName, out var newInstance))
            {
#if x86
                if (Environment.Is64BitOperatingSystem)
                {
                    var curPath64 = PathEx.Combine(PathEx.LocalDir, $"{ProcessEx.CurrentName}64.exe");
                    if (File.Exists(curPath64))
                    {
                        ProcessEx.Start(curPath64, EnvironmentEx.CommandLine(false));
                        return;
                    }
                }
#endif

                if (!string.IsNullOrWhiteSpace(Attributes.DefIni) && !string.IsNullOrWhiteSpace(Attributes.ConfigPath) && !File.Exists(Attributes.ConfigPath))
                {
                    try
                    {
                        File.WriteAllText(Attributes.ConfigPath, Attributes.DefIni);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        Elevation.RestartAsAdministrator();
                    }
                }
예제 #2
0
        private static void Main()
        {
            Log.AllowLogging();
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                var appPath = PathEx.Combine(PathEx.LocalDir, "App\\hexeditmx\\hexeditmx.exe");
                if (!File.Exists(appPath))
                {
                    return;
                }

                if (!newInstance)
                {
                    ProcessEx.Start(appPath, EnvironmentEx.CommandLine());
                    return;
                }

                if (ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(appPath)))
                {
                    return;
                }

                var regKeys = new[]
                {
                    "HKCU\\Software\\NEXT-Soft"
                };

                Helper.RegForwarding(Helper.Options.Start, regKeys);

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(), false);

                Helper.RegForwarding(Helper.Options.Exit, regKeys);
            }
        }
예제 #3
0
        private static void Main()
        {
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                if (!newInstance)
                {
                    return;
                }

                var appPath = PathEx.Combine(PathEx.LocalDir, "App\\SharpKeys\\SharpKeys.exe");
                if (!File.Exists(appPath))
                {
                    return;
                }

                const string firstKey = "HKCU\\Software\\RandyRants";
                const string lastKey  = "HKCU\\Software\\RandyRants\\SharpKeys";

                Helper.RegForwarding(Helper.Options.Start, lastKey);
                Reg.Write(lastKey, "ShowWarning", 1, RegistryValueKind.DWord);

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(false), false);

                Helper.RegForwarding(Helper.Options.Exit, firstKey);
                if (!Reg.GetSubKeys(firstKey).Any())
                {
                    Reg.RemoveSubKey(firstKey);
                }
            }
        }
예제 #4
0
        private void ScBtn_Click(object sender, EventArgs e)
        {
            var dir = PathEx.Combine(DirTB.Text);

            if (!Directory.Exists(dir))
            {
                return;
            }
            var path = PathEx.Combine(FilePathTB.Text);

            if (!File.Exists(path))
            {
                return;
            }
            var arguments = ArgsTB.Text;

            if (!string.IsNullOrWhiteSpace(arguments))
            {
                arguments = $" -- {arguments}";
            }
            arguments = string.Format(Resources.Args, EnvironmentEx.GetVariablePathFull(path, false), arguments).TrimEnd();
            var script  = PathEx.Combine(string.Format(Resources.ScriptPath, Path.GetFileName(path), new Crypto.Md5().EncryptFile(path)));
            var content = string.Format(Resources.ScriptDummy, EnvironmentEx.GetVariablePathFull(_appPath, false), EnvironmentEx.GetVariablePathFull(dir, false), arguments);

            File.WriteAllText(script, content);
            MessageBoxEx.Show(this, Resources.Msg_Hint_01, Resources.WindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            ProcessEx.Start(Resources.ExplorerPath, Path.GetDirectoryName(script));
        }
예제 #5
0
        public SettingsForm()
        {
            InitializeComponent();

            Language.SetControlLang(this);
            foreach (var label in groupColorsGroupBox.Controls.OfType <Label>())
            {
                if (string.IsNullOrEmpty(label.Text) || label.Text.EndsWith(":"))
                {
                    continue;
                }
                label.Text += ':';
            }

            Icon = CacheData.GetSystemIcon(ResourcesEx.IconIndex.SystemControl);

            transferPathBox.Text                = EnvironmentEx.GetVariablePathFull(Settings.TransferDir, false, false);
            transferPathBtn.BackgroundImage     = CacheData.GetSystemImage(ResourcesEx.IconIndex.Directory);
            transferPathUndoBtn.BackgroundImage = CacheData.GetSystemImage(ResourcesEx.IconIndex.Undo);
            if (Settings.TransferDir.EqualsEx(CorePaths.TransferDir))
            {
                transferPathUndoBtn.Enabled         = false;
                transferPathUndoBtn.BackgroundImage = transferPathUndoBtn.BackgroundImage.SwitchGrayScale(transferPathUndoBtn);
            }

            appListGroupBox.ResumeLayout(false);
            appListGroupBox.PerformLayout();
            groupColorsGroupBox.ResumeLayout(false);
            ((ISupportInitialize)logoBox).EndInit();
            transferGroupBox.ResumeLayout(false);
            transferGroupBox.PerformLayout();
            advancedGroupBox.ResumeLayout(false);
            ResumeLayout(false);
        }
예제 #6
0
        private static void Main()
        {
            Log.AllowLogging();
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                if (!newInstance)
                {
                    return;
                }

                var appDir = PathEx.Combine(PathEx.LocalDir, "App\\Defraggler");
                if (!Directory.Exists(appDir))
                {
                    return;
                }

                var appPath     = Path.Combine(appDir, "Defraggler.exe");
                var updaterPath = Path.Combine(appDir, "DefragglerUpdater.exe");
                if (ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(appPath)) || !File.Exists(updaterPath) || ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(updaterPath)))
                {
                    return;
                }

                var dataDir = PathEx.Combine(PathEx.LocalDir, "Data");
                var fileMap = new Dictionary <string, string>
                {
                    {
                        PathEx.Combine(appDir, "defraggler.ini"),
                        PathEx.Combine(dataDir, "defraggler.ini")
                    },
                    {
                        PathEx.Combine(appDir, "statistics.bin"),
                        PathEx.Combine(dataDir, "statistics.bin")
                    }
                };

                Helper.ApplicationStart(updaterPath, "/silent", null);
                if (!File.Exists(appPath))
                {
                    var updIniPath = Path.ChangeExtension(updaterPath, ".ini");
                    if (!string.IsNullOrEmpty(updIniPath) && File.Exists(updIniPath))
                    {
                        File.Delete(updIniPath);
                    }
                    return;
                }

                Helper.FileForwarding(Helper.Options.Start, fileMap);

                var portableDat = Path.Combine(appDir, "portable.dat");
                if (!File.Exists(portableDat))
                {
                    File.WriteAllText(portableDat, @"#PORTABLE#");
                }

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(false), false);

                Helper.FileForwarding(Helper.Options.Exit, fileMap);
            }
        }
예제 #7
0
        public SettingsForm()
        {
            InitializeComponent();

            SuspendLayout();

            Language.SetControlLang(this);
            foreach (var label in groupColorsGroupBox.Controls.OfType <Label>())
            {
                if (string.IsNullOrEmpty(label.Text) || label.Text.EndsWith(":", StringComparison.Ordinal))
                {
                    continue;
                }
                label.Text += ':';
            }

            Icon = CacheData.GetSystemIcon(ImageResourceSymbol.SystemControl);

            transferPathBox.Text                = EnvironmentEx.GetVariablePathFull(Settings.TransferDir, false, false);
            transferPathBtn.BackgroundImage     = CacheData.GetSystemImage(ImageResourceSymbol.Directory);
            transferPathUndoBtn.BackgroundImage = CacheData.GetSystemImage(ImageResourceSymbol.Undo);
            if (Settings.TransferDir.EqualsEx(CorePaths.TransferDir))
            {
                transferPathUndoBtn.Enabled         = false;
                transferPathUndoBtn.BackgroundImage = transferPathUndoBtn.BackgroundImage.SwitchGrayScale(transferPathUndoBtn);
            }

            ResumeLayout(false);
        }
예제 #8
0
        private static void Main()
        {
            Log.AllowLogging();
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                if (!newInstance)
                {
                    return;
                }

                var appPath = PathEx.Combine(PathEx.LocalDir, "App\\AIDA64\\aida64.exe");
                if (!File.Exists(appPath) || ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(appPath)))
                {
                    return;
                }

                const string iniPath = "%CurDir%\\Data\\aida64.ini";
                var          iniMap  = new Dictionary <string, Dictionary <string, string> >
                {
                    {
                        "Generic", new Dictionary <string, string>
                        {
                            {
                                "NoRegistry",
                                "1"
                            },
                            {
                                "NetUpdateFreq",
                                "1"
                            },
                            {
                                "ReportFileFolder",
                                PathEx.Combine(PathEx.LocalDir, "Data\\Reports")
                            }
                        }
                    }
                };

                var fileMap = new Dictionary <string, string>
                {
                    {
                        "%CurDir%\\App\\AIDA64\\aida64.ini",
                        "%CurDir%\\Data\\aida64.ini"
                    },
                    {
                        "%CurDir%\\App\\AIDA64\\aida64.reg.ini",
                        "%CurDir%\\Data\\aida64.reg.ini"
                    }
                };

                Helper.ConfigOverwrite(iniMap, iniPath);

                Helper.FileForwarding(Helper.Options.Start, fileMap, true);

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(false), false);

                Helper.FileForwarding(Helper.Options.Exit, fileMap, true);
            }
        }
예제 #9
0
        static bool IsDisable()
        {
            var variable = EnvironmentEx.GetEnvironmentVariable("DiffEngine_Disabled");

            return(string.Equals(variable, "true", StringComparison.OrdinalIgnoreCase) ||
                   BuildServerDetector.Detected ||
                   ContinuousTestingDetector.Detected);
        }
예제 #10
0
 public void Found()
 {
     Environment.SetEnvironmentVariable("AB", "Value1");
     Environment.SetEnvironmentVariable("A.B", "Value2");
     Environment.SetEnvironmentVariable("A_C", "Value3");
     Assert.Equal("Value1", EnvironmentEx.GetEnvironmentVariable("AB"));
     Assert.Equal("Value2", EnvironmentEx.GetEnvironmentVariable("A_B"));
     Assert.Equal("Value3", EnvironmentEx.GetEnvironmentVariable("A_C"));
 }
예제 #11
0
        public void GetFileSystemRootPath()
        {
            string fileSystemRoot = EnvironmentEx.GetFileSystemRoot();

            TestContext.WriteLine(fileSystemRoot);

            fileSystemRoot.Should().Be(Path.GetFullPath(fileSystemRoot));
            Directory.Exists(fileSystemRoot).Should().BeTrue();
        }
예제 #12
0
        internal static void UpdateStartMenuShortcuts(IEnumerable <string> longAppNames)
        {
            var appNames = longAppNames?.ToArray();

            if (appNames?.Any() != true)
            {
                return;
            }
            try
            {
                var startMenuDir = PathEx.Combine(Environment.SpecialFolder.StartMenu, "Programs");
#if x86
                var shortcutPath = Path.Combine(startMenuDir, "Apps Launcher.lnk");
#else
                var shortcutPath = Path.Combine(startMenuDir, "Apps Launcher (64-bit).lnk");
#endif
                if (Directory.Exists(startMenuDir))
                {
                    var shortcuts = Directory.GetFiles(startMenuDir, "Apps Launcher*.lnk", SearchOption.TopDirectoryOnly);
                    if (shortcuts.Length > 0)
                    {
                        foreach (var shortcut in shortcuts)
                        {
                            File.Delete(shortcut);
                        }
                    }
                }
                if (!Directory.Exists(startMenuDir))
                {
                    Directory.CreateDirectory(startMenuDir);
                }
                FileEx.CreateShellLink(EnvironmentEx.GetVariablePathFull(PathEx.LocalPath, false), shortcutPath);
                startMenuDir = Path.Combine(startMenuDir, "Portable Apps");
                if (Directory.Exists(startMenuDir))
                {
                    var shortcuts = Directory.GetFiles(startMenuDir, "*.lnk", SearchOption.TopDirectoryOnly);
                    if (shortcuts.Length > 0)
                    {
                        foreach (var shortcut in shortcuts)
                        {
                            File.Delete(shortcut);
                        }
                    }
                }
                if (!Directory.Exists(startMenuDir))
                {
                    Directory.CreateDirectory(startMenuDir);
                }
                Parallel.ForEach(appNames, x => FileEx.CreateShellLink(EnvironmentEx.GetVariablePathFull(CacheData.FindAppData(x)?.FilePath, false, false), Path.Combine(startMenuDir, x)));
            }
            catch (Exception ex)
            {
                Log.Write(ex);
            }
        }
예제 #13
0
 private void TransferPathUndoBtn_Click(object sender, EventArgs e)
 {
     Settings.TransferDir = CorePaths.TransferDir;
     transferPathBox.Text = EnvironmentEx.GetVariablePathFull(Settings.TransferDir, false, false);
     if (transferPathUndoBtn.Enabled)
     {
         transferPathUndoBtn.Enabled         = false;
         transferPathUndoBtn.BackgroundImage = transferPathUndoBtn.BackgroundImage.SwitchGrayScale(transferPathUndoBtn);
     }
     MessageBoxEx.Show(this, Language.GetText(nameof(en_US.OperationCompletedMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
 }
예제 #14
0
        private static void Main()
        {
            Log.AllowLogging();
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                if (!newInstance)
                {
                    return;
                }

                var appPath = PathEx.Combine("%CurDir%\\App\\FormatFactory\\FormatFactory.exe");
                if (!File.Exists(appPath) || ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(appPath)))
                {
                    return;
                }

                var regKeys = new[]
                {
                    "HKCU\\Software\\FreeTime",
                    "HKCU\\Software\\FreeTime\\FormatFactory"
                };

                Helper.RegForwarding(Helper.Options.Start, regKeys[0]);

                Reg.Write(regKeys[0], "FormatFactory", Path.GetDirectoryName(appPath), RegistryValueKind.String);
                Reg.Write(regKeys[1], "CheckNewVersion", 0, RegistryValueKind.DWord);
                Reg.Write(regKeys[1], "CodecInstalled", 0, RegistryValueKind.DWord);
                Reg.Write(regKeys[1], "OptionActivePage", 0, RegistryValueKind.DWord);
                Reg.Write(regKeys[1], "OutputDir", PathEx.Combine("%CurDir%\\Data\\Output"), RegistryValueKind.String);
                Reg.Write(regKeys[1], "UseCount", 1, RegistryValueKind.DWord);
#if Legacy
                Reg.Write(regKeys[1], "Skin", 2, RegistryValueKind.DWord);
                Reg.Write(regKeys[1], "Version", "3.3.5", RegistryValueKind.String);
#else
                Reg.Write(regKeys[1], "Skin", 6, RegistryValueKind.DWord);
                Reg.Write(regKeys[1], "StartMethodTab", 0, RegistryValueKind.DWord);
                try
                {
                    var fvi = FileVersionInfo.GetVersionInfo(appPath);
                    var str = new List <string>(fvi.ProductVersion.Split('.')).GetRange(0, 3).Join('.');
                    Reg.Write(regKeys[1], "Version", str, RegistryValueKind.String);
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                }
#endif

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(false), false);

                Helper.RegForwarding(Helper.Options.Exit, regKeys[0]);
            }
        }
예제 #15
0
        private static void Main()
        {
            InitializeConsole();
            foreach (var arg in EnvironmentEx.CommandLineArgs(true, 1, false))
            {
                if (_active)
                {
                    Console.WriteLine();
                    Console.WriteLine();
                }
                var file = PathEx.Combine(arg);
                if (!File.Exists(file))
                {
                    WriteInnerLine($"Cannot find \'{file}\'", "Error", ErrorCaptionFgColor);
                    continue;
                }
                try
                {
                    var name = Path.GetFileName(file);
                    if (!string.IsNullOrWhiteSpace(name))
                    {
                        WriteInnerLine(name, "File", !name.EndsWithEx(".exe", ".dll") ? WarnCaptionFgColor : DefaultCaptionFgColor);
                    }

                    var version = FileEx.GetFileVersion(file)?.ToString();
                    if (!string.IsNullOrWhiteSpace(version) && !version.Equals("0.0.0.0"))
                    {
                        WriteInnerLine(version, "Version", DefaultCaptionFgColor);
                    }

                    var subject = FileEx.GetSignatureSubject(file);
                    if (!string.IsNullOrWhiteSpace(subject))
                    {
                        WriteInnerLine(subject, "Subject", DefaultCaptionFgColor);
                    }

                    var status = FileEx.GetSignatureStatus(file);
                    if (!string.IsNullOrWhiteSpace(status))
                    {
                        WriteInnerLine(status, "Status", status.ContainsEx("Unknown", "Error") ? ErrorCaptionFgColor : status.ContainsEx("NotSigned") ? WarnCaptionFgColor : DefaultCaptionFgColor);
                    }
                }
                catch (Exception ex) when(ex.IsCaught())
                {
                    WriteInnerLine(ex.Message, "Error", ErrorCaptionFgColor);
                }
            }
            ExitConsole();
        }
        static TabTipAutomation()
        {
            if (EnvironmentEx.GetOSVersion() == OSVersion.Win7)
            {
                return;
            }

            TabTip.Closed += () => TabTipClosedSubject.OnNext(true);

            AutomateTabTipOpen(FocusSubject.AsObservable());
            AutomateTabTipClose(FocusSubject.AsObservable(), TabTipClosedSubject);

            AnimationHelper.ExceptionCatched += exception => ExceptionCatched?.Invoke(exception);
            TabTip.ExceptionCatched          += exception => ExceptionCatched?.Invoke(exception);
        }
예제 #17
0
    static int GetMaxInstances()
    {
        var variable = EnvironmentEx.GetEnvironmentVariable("DiffEngine_MaxInstances");

        if (string.IsNullOrEmpty(variable))
        {
            return(5);
        }

        if (ushort.TryParse(variable, out var result))
        {
            return(result);
        }

        throw new Exception($"Could not parse the DiffEngine_MaxInstances environment variable: {variable}");
    }
예제 #18
0
파일: UpdateManager.cs 프로젝트: ND6/Onova
        /// <inheritdoc />
        public void LaunchUpdater(Version version, bool restart = true)
        {
            // Ensure that the current state is valid for this operation
            EnsureNotDisposed();
            EnsureLockFileAcquired();
            EnsureUpdaterNotLaunched();
            EnsureUpdatePrepared(version);

            // Get package content directory path
            var packageContentDirPath = GetPackageContentDirPath(version);

            // Get original command line arguments and encode them to avoid issues with quotes
            var routedArgs = EnvironmentEx.GetCommandLineWithoutExecutable().GetString().ToBase64();

            // Prepare arguments
            var updaterArgs = $"\"{_updatee.FilePath}\" \"{packageContentDirPath}\" \"{restart}\" \"{routedArgs}\"";

            // Decide if updater needs to be elevated
            var updateeDirPath    = Path.GetDirectoryName(_updatee.FilePath);
            var isUpdaterElevated = !DirectoryEx.CheckWriteAccess(updateeDirPath);

            // Create updater process start info
            var updaterStartInfo = new ProcessStartInfo
            {
                FileName        = _updaterFilePath,
                Arguments       = updaterArgs,
                CreateNoWindow  = true,
                UseShellExecute = false
            };

            // If updater needs to be elevated - use shell execute with "runas"
            if (isUpdaterElevated)
            {
                updaterStartInfo.Verb            = "runas";
                updaterStartInfo.UseShellExecute = true;
            }

            // Create and start updater process
            var updaterProcess = new Process {
                StartInfo = updaterStartInfo
            };

            using (updaterProcess)
                updaterProcess.Start();
        }
    public int Run(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += (_, e) => ReportError(e.ExceptionObject.ToString());

        try
        {
            var targetAssembly = TargetAssembly.Resolve();

            try
            {
                // Hot path: attempt to run the target first without any checks
                return(targetAssembly.Run(args));
            }
            // Possible exception causes:
            // - .NET host not found (DirectoryNotFoundException)
            // - .NET host failed to initialize (ApplicationException)
            catch
            {
                // Check for and install missing prerequisites
                var missingPrerequisites = targetAssembly.GetMissingPrerequisites();
                if (missingPrerequisites.Any())
                {
                    var isInstallationSuccessful = InstallPrerequisites(targetAssembly, missingPrerequisites);

                    // User canceled installation or reboot is required
                    if (!isInstallationSuccessful)
                    {
                        return(0xB007);
                    }

                    // Reset environment to update PATH and other variables
                    // that may have been changed by the installation process.
                    EnvironmentEx.RefreshEnvironmentVariables();
                }

                // Attempt to run the target again, this time without ignoring exceptions
                return(targetAssembly.Run(args));
            }
        }
        catch (Exception ex)
        {
            ReportError(ex.ToString());
            return(0xDEAD);
        }
    }
예제 #20
0
        internal static void RepairEnvironmentVariable()
        {
            if (!Elevation.IsAdministrator)
            {
                using (var process = ProcessEx.Start(PathEx.LocalPath, ActionGuid.RepairVariable, true, false))
                    if (process?.HasExited == false)
                    {
                        process.WaitForExit();
                    }
                return;
            }
            var envDir = EnvironmentEx.GetVariableValue(Settings.EnvironmentVariable);

            if (!Settings.DeveloperVersion && !string.IsNullOrWhiteSpace(envDir) && !envDir.EqualsEx(PathEx.LocalDir))
            {
                SystemIntegration.Enable(true, true);
            }
        }
예제 #21
0
        internal static void Initialize()
        {
#if x86
            if (Environment.Is64BitOperatingSystem)
            {
                var appsDownloader64 = PathEx.Combine(PathEx.LocalDir, $"{ProcessEx.CurrentName}64.exe");
                if (File.Exists(appsDownloader64))
                {
                    ProcessEx.Start(appsDownloader64, EnvironmentEx.CommandLine(false));
                    Environment.ExitCode = 0;
                    Environment.Exit(Environment.ExitCode);
                }
            }
#endif

            Log.FileDir = Path.Combine(CorePaths.TempDir, "Logs");

            Ini.SetFile(PathEx.LocalDir, "..", "Settings.ini");
            Ini.SortBySections = new[]
            {
                Section,
                "Launcher"
            };

            Log.AllowLogging(Ini.FilePath, "DebugMode", Ini.GetRegex(false));

            if (Elevation.IsAdministrator)
            {
                var path = Path.Combine("HKCU\\Software\\Portable Apps Suite", CorePaths.HomeDir.Encrypt(ChecksumAlgorithms.Adler32), ProcessEx.CurrentId.ToString());
                if (Reg.CreateNewSubKey(path))
                {
                    AppDomain.CurrentDomain.ProcessExit += (s, e) => Reg.RemoveSubKey(path);
                }
            }

            if (Recovery.AppsSuiteIsHealthy())
            {
                return;
            }
            Environment.ExitCode = 1;
            Environment.Exit(Environment.ExitCode);
        }
예제 #22
0
        private static void Main()
        {
            Log.AllowLogging();
            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                var appPath = PathEx.Combine(PathEx.LocalDir, "App\\mpTrim\\mpTrim.exe");
                if (!File.Exists(appPath))
                {
                    return;
                }

                if (!newInstance)
                {
                    ProcessEx.Start(appPath, EnvironmentEx.CommandLine(false));
                    return;
                }

                const string regKey = "HKCU\\Software\\mpTrim";
                Helper.RegForwarding(Helper.Options.Start, regKey);

                var regPath = PathEx.Combine(PathEx.LocalDir, "Data\\settings.reg");
                if (!File.Exists(regPath))
                {
                    var       screenWidth = Screen.PrimaryScreen.WorkingArea.Width;
                    const int windowWidth = 335;
                    var       windowLeft  = (int)Math.Round(screenWidth / 2d - windowWidth / 2d);
                    Reg.Write(regKey, "MainFormLeft", windowLeft, RegistryValueKind.DWord);

                    var       screenHeight = Screen.PrimaryScreen.WorkingArea.Height;
                    const int windowHeight = 410;
                    var       windowTop    = (int)Math.Round(screenHeight / 2d - windowHeight / 2d);
                    Reg.Write(regKey, "MainFormTop", windowTop, RegistryValueKind.DWord);
                }

                Helper.ApplicationStart(appPath, EnvironmentEx.CommandLine(false), false);

                Helper.RegForwarding(Helper.Options.Exit, regKey);
            }
        }
예제 #23
0
 private void TransferPathBtn_Click(object sender, EventArgs e)
 {
     using (var dialog = new FolderBrowserDialog())
     {
         dialog.SelectedPath = Path.GetTempPath();
         if (dialog.ShowDialog() != DialogResult.OK)
         {
             MessageBoxEx.Show(this, Language.GetText(nameof(en_US.OperationCanceledMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
             return;
         }
         var transferDir = dialog.SelectedPath;
         if (transferDir.EqualsEx(Settings.TransferDir))
         {
             MessageBoxEx.Show(this, Language.GetText(nameof(en_US.OperationFailedMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
             return;
         }
         var currentDrive  = PathEx.LocalPath.ToUpperInvariant().First();
         var transferDrive = transferDir.ToUpperInvariant().First();
         if (currentDrive.Equals(transferDrive))
         {
             MessageBoxEx.Show(this, Language.GetText(nameof(en_US.TransferDirMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
             return;
         }
         var currentDir = Settings.TransferDir;
         Settings.TransferDir = transferDir;
         var dirChanged = !Settings.TransferDir.EqualsEx(currentDir);
         if (dirChanged)
         {
             transferPathBox.Text = EnvironmentEx.GetVariablePathFull(Settings.TransferDir, false, false);
             if (!transferPathUndoBtn.Enabled)
             {
                 transferPathUndoBtn.Enabled         = true;
                 transferPathUndoBtn.BackgroundImage = transferPathUndoBtn.BackgroundImage.SwitchGrayScale(transferPathUndoBtn);
             }
         }
         MessageBoxEx.Show(this, Language.GetText(dirChanged ? nameof(en_US.OperationCompletedMsg) : nameof(en_US.OperationFailedMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, dirChanged ? MessageBoxIcon.Asterisk : MessageBoxIcon.Warning);
     }
 }
예제 #24
0
 /// <summary>
 /// Launches an external executable that will apply an update to given version, once this application exits.
 /// The updater can be instructed to also restart the application after it's updated.
 /// If the application is to be restarted, it will receive the same command line arguments as it did initially.
 /// </summary>
 public static void LaunchUpdater(this IUpdateManager manager, Version version, bool restart = true) =>
 manager.LaunchUpdater(version, restart, EnvironmentEx.GetCommandLineWithoutExecutable());
예제 #25
0
        internal static void Enable(bool enabled, bool quiet = false)
        {
            if (!Elevation.IsAdministrator)
            {
                using (var process = ProcessEx.Start(PathEx.LocalPath, $"{ActionGuid.SystemIntegration} {enabled}", true, false))
                    if (process?.HasExited == false)
                    {
                        process.WaitForExit();
                    }
                return;
            }
            var varKey = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
            var varDir = Reg.ReadString(Registry.LocalMachine, varKey, Settings.EnvironmentVariable);
            var curDir = PathEx.LocalDir;

            if (!enabled || !varDir.EqualsEx(curDir))
            {
                var curPath    = EnvironmentEx.GetVariablePathFull(PathEx.LocalPath, false);
                var sendToPath = PathEx.Combine(Environment.SpecialFolder.SendTo, "Apps Launcher.lnk");
                if (enabled)
                {
                    Reg.Write(Registry.LocalMachine, varKey, Settings.EnvironmentVariable, curDir);
                    FileEx.CreateShellLink(curPath, sendToPath);
                }
                else
                {
                    Reg.RemoveEntry(Registry.LocalMachine, varKey, Settings.EnvironmentVariable);
                    PathEx.ForceDelete(sendToPath);
                }
                if (WinApi.NativeHelper.SendNotifyMessage((IntPtr)0xffff, (uint)WinApi.WindowMenuFlags.WmSettingChange, (UIntPtr)0, "Environment"))
                {
                    foreach (var baseKey in new[]
                    {
                        "*",
                        "Folder"
                    })
                    {
                        varKey = Path.Combine(baseKey, "shell\\portableapps");
                        if (enabled)
                        {
                            if (string.IsNullOrWhiteSpace(Reg.ReadString(Registry.ClassesRoot, varKey, null)))
                            {
                                Reg.Write(Registry.ClassesRoot, varKey, null, Language.GetText(nameof(en_US.shellText)));
                            }
                            Reg.Write(Registry.ClassesRoot, varKey, "Icon", $"\"{PathEx.LocalPath}\"");
                        }
                        else
                        {
                            Reg.RemoveSubKey(Registry.ClassesRoot, varKey);
                        }
                        varKey = Path.Combine(varKey, "command");
                        if (enabled)
                        {
                            Reg.Write(Registry.ClassesRoot, varKey, null, $"\"{PathEx.LocalPath}\" \"%1\"");
                        }
                        else
                        {
                            Reg.RemoveSubKey(Registry.ClassesRoot, varKey);
                        }
                    }
                    if (enabled)
                    {
                        if (TaskBar.Pin(PathEx.LocalPath))
                        {
                            var pinnedDir = PathEx.Combine(Environment.SpecialFolder.ApplicationData, "Microsoft", "Internet Explorer", "Quick Launch", "User Pinned", "TaskBar");
                            foreach (var file in Directory.GetFiles(pinnedDir, "*.lnk", SearchOption.TopDirectoryOnly))
                            {
                                if (!string.Equals(FileEx.GetShellLinkTarget(file), PathEx.LocalPath, StringComparison.CurrentCultureIgnoreCase))
                                {
                                    continue;
                                }
                                ProcessEx.SendHelper.Delete(file);
                                Environment.SetEnvironmentVariable(Settings.EnvironmentVariable, curDir, EnvironmentVariableTarget.Process);
                                FileEx.CreateShellLink(curPath, file);
                                break;
                            }
                        }
                    }
                    else
                    {
                        TaskBar.Unpin(PathEx.LocalPath);
                    }

                    if (enabled)
                    {
                        using (var process = ProcessEx.Start(PathEx.LocalPath, ActionGuid.FileTypeAssociationAll, true, false))
                            if (process?.HasExited == false)
                            {
                                process.WaitForExit();
                            }
                    }

                    if (!quiet)
                    {
                        MessageBox.Show(Language.GetText(nameof(en_US.OperationCompletedMsg)), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    return;
                }
            }
            if (!quiet)
            {
                MessageBox.Show(Language.GetText(nameof(en_US.OperationCanceledMsg)), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
예제 #26
0
        private static void Main()
        {
            Log.AllowLogging();
#if x86
            var curPath64 = PathEx.Combine(PathEx.LocalDir, "VLC64Portable.exe");
            if (Environment.Is64BitOperatingSystem && File.Exists(curPath64))
            {
                ProcessEx.Start(curPath64, EnvironmentEx.CommandLine());
                return;
            }
            var appDir      = PathEx.Combine(PathEx.LocalDir, "App\\vlc");
            var updaterPath = PathEx.Combine(appDir, "VLCUpdater.exe");
#else
            var appDir      = PathEx.Combine(PathEx.LocalDir, "App\\vlc64");
            var updaterPath = PathEx.Combine(appDir, "VLCUpdater64.exe");
#endif

            if (!File.Exists(updaterPath) || ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(updaterPath)))
            {
                return;
            }

            using (new Mutex(true, ProcessEx.CurrentName, out bool newInstance))
            {
                var appPath = PathEx.Combine(appDir, "vlc.exe");

                if (!newInstance)
                {
                    ProcessEx.Start(appPath, EnvironmentEx.CommandLine());
                    return;
                }

                if (ProcessEx.IsRunning(Path.GetFileNameWithoutExtension(appPath)))
                {
                    return;
                }

                var dirMap = new Dictionary <string, string>
                {
                    {
                        "%AppData%\\vlc",
                        "%CurDir%\\Data"
                    }
                };

                Helper.ApplicationStart(updaterPath, "/silent", null);
                if (!File.Exists(appPath))
                {
                    var updIniPath = Path.ChangeExtension(updaterPath, ".ini");
                    if (!string.IsNullOrEmpty(updIniPath) && File.Exists(updIniPath))
                    {
                        File.Delete(updIniPath);
                    }
                    return;
                }

                Helper.DirectoryForwarding(Helper.Options.Start, dirMap);

                Helper.ApplicationStart(appPath, $"{EnvironmentEx.CommandLine()} --no-plugins-cache");

                Helper.DirectoryForwarding(Helper.Options.Exit, dirMap);
            }
        }
예제 #27
0
        private void SaveBtn_Click(object sender, EventArgs e)
        {
            var appData = CacheData.FindAppData(appsBox.SelectedItem.ToString());

            if (appData != default)
            {
                if (string.IsNullOrWhiteSpace(fileTypes.Text))
                {
                    appData.Settings.FileTypes = default;
                }
                else
                {
                    if (e == EventArgs.Empty || !FileTypesConflict())
                    {
                        var typesList = new List <string>();
                        foreach (var item in $"{fileTypes.Text},".Split(','))
                        {
                            if (string.IsNullOrWhiteSpace(item))
                            {
                                continue;
                            }
                            var type = new string(item.ToCharArray().Where(c => !Path.GetInvalidFileNameChars().Contains(c) && !char.IsWhiteSpace(c)).ToArray());
                            if (string.IsNullOrWhiteSpace(type) || type.Length < 1)
                            {
                                continue;
                            }
                            if (type.StartsWith(".", StringComparison.Ordinal))
                            {
                                while (type.Contains(".."))
                                {
                                    type = type.Replace("..", ".");
                                }
                                if (typesList.ContainsItem(type) || typesList.ContainsItem(type.Substring(1)))
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                if (typesList.ContainsItem(type) || typesList.ContainsItem($".{type}"))
                                {
                                    continue;
                                }
                            }
                            if (type.Length == 1 && type.StartsWith(".", StringComparison.Ordinal))
                            {
                                continue;
                            }
                            typesList.Add(type);
                        }
                        if (typesList.Any())
                        {
                            var comparer = new AlphaNumericComparer <string>();
                            typesList                  = typesList.OrderBy(x => x, comparer).ToList();
                            fileTypes.Text             = typesList.Join(",");
                            appData.Settings.FileTypes = new Collection <string>(typesList);
                        }
                    }
                    else
                    {
                        fileTypes.Text = appData.Settings.FileTypes.Join(',');
                    }
                }

                appData.Settings.StartArgsFirst = startArgsFirst.Text;
                appData.Settings.StartArgsLast  = startArgsLast.Text;

                appData.Settings.SortArgPaths = sortArgPathsCheck.Checked;
                appData.Settings.NoConfirm    = noConfirmCheck.Checked;
                appData.Settings.RunAsAdmin   = runAsAdminCheck.Checked;
                appData.Settings.NoUpdates    = noUpdatesCheck.Checked;
            }

            if (defBgCheck.Checked)
            {
                if (CacheData.CurrentImageBg != default)
                {
                    CacheData.CurrentImageBg = default;
                    if (Result != DialogResult.Yes)
                    {
                        Result = DialogResult.Yes;
                    }
                }
                bgLayout.SelectedIndex = 1;
            }

            Settings.Window.FadeInEffect   = (Settings.Window.FadeInEffectOptions)fadeInCombo.SelectedIndex;
            Settings.Window.FadeInDuration = (int)fadeInNum.Value;
            Settings.Window.Opacity        = (double)opacityNum.Value;

            Settings.Window.BackgroundImageLayout = (ImageLayout)bgLayout.SelectedIndex;

            Settings.Window.Colors.Base        = mainColorPanel.BackColor;
            Settings.Window.Colors.Control     = controlColorPanel.BackColor;
            Settings.Window.Colors.ControlText = controlTextColorPanel.BackColor;
            Settings.Window.Colors.Button      = btnColorPanel.BackColor;
            Settings.Window.Colors.ButtonHover = btnHoverColorPanel.BackColor;
            Settings.Window.Colors.ButtonText  = btnTextColorPanel.BackColor;

            Settings.Window.HideHScrollBar = hScrollBarCheck.Checked;
            Settings.Window.LargeImages    = showLargeImagesCheck.Checked;

            var dirList = new List <string>();

            if (!string.IsNullOrWhiteSpace(appDirs.Text))
            {
                var tmpDir = appDirs.Text + Environment.NewLine;
                foreach (var item in tmpDir.SplitNewLine())
                {
                    if (string.IsNullOrWhiteSpace(item))
                    {
                        continue;
                    }
                    var dir = PathEx.Combine(item);
                    try
                    {
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        dir = EnvironmentEx.GetVariableWithPath(dir);
                        if (!dirList.ContainsItem(dir))
                        {
                            dirList.Add(dir);
                        }
                    }
                    catch (Exception ex) when(ex.IsCaught())
                    {
                        Log.Write(ex);
                    }
                }
                if (dirList.Count > 0)
                {
                    dirList.Sort();
                    appDirs.Text = dirList.Join(Environment.NewLine);
                }
            }
            Settings.AppDirs = dirList.ToArray();

            Settings.StartMenuIntegration = startMenuIntegration.SelectedIndex > 0;
            if (!Settings.StartMenuIntegration)
            {
                try
                {
                    var shortcutDirs = new[]
                    {
                        Environment.GetFolderPath(Environment.SpecialFolder.SendTo),
                        PathEx.Combine(Environment.SpecialFolder.StartMenu, "Programs")
                    };
                    foreach (var dir in shortcutDirs)
                    {
                        var shortcuts = Directory.GetFiles(dir, "Apps Launcher*.lnk", SearchOption.TopDirectoryOnly);
                        foreach (var shortcut in shortcuts.Where(File.Exists))
                        {
                            File.Delete(shortcut);
                        }
                    }
                    var startMenuDir = Path.Combine(shortcutDirs.Last(), "Portable Apps");
                    if (Directory.Exists(startMenuDir))
                    {
                        Directory.Delete(startMenuDir, true);
                    }
                }
                catch (Exception ex) when(ex.IsCaught())
                {
                    Log.Write(ex);
                }
            }

            Settings.Window.DefaultPosition = defaultPos.SelectedIndex;

            Settings.UpdateCheck   = (Settings.UpdateCheckOptions)updateCheck.SelectedIndex;
            Settings.UpdateChannel = (Settings.UpdateChannelOptions)updateChannel.SelectedIndex;

            var lang = setLang.SelectedItem.ToString();

            if (!Settings.Language.EqualsEx(lang))
            {
                if (Result != DialogResult.Yes)
                {
                    Result = DialogResult.Yes;
                }
                Settings.Language = lang;
                LoadSettings();
            }

            Settings.WriteToFile();

            MessageBoxEx.Show(this, Language.GetText(nameof(en_US.SavedSettings)), MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }
예제 #28
0
        private void LoadSettings()
        {
            if (!setLang.Items.Contains(Settings.Language))
            {
                Settings.Language = "en-US";
            }
            setLang.SelectedItem = Settings.Language;
            Language.UserLang    = Settings.Language;

            Language.SetControlLang(this);

            var title = Language.GetText(nameof(en_US.settingsBtn));

            if (!string.IsNullOrWhiteSpace(title))
            {
                Text = title;
            }

            for (var i = 0; i < fileTypesMenu.Items.Count; i++)
            {
                fileTypesMenu.Items[i].Text = Language.GetText(fileTypesMenu.Items[i].Name);
            }

            var decValue = (decimal)Settings.Window.Opacity;

            opacityNum.Value = decValue >= opacityNum.Minimum && decValue <= opacityNum.Maximum ? decValue : .95m;

            var intValue = (int)Settings.Window.FadeInEffect;

            fadeInCombo.SelectedIndex = intValue < fadeInCombo.Items.Count ? intValue : 0;

            intValue        = Settings.Window.FadeInDuration;
            fadeInNum.Value = intValue >= fadeInNum.Minimum && intValue <= fadeInNum.Maximum ? intValue : 100;

            defBgCheck.Checked = !File.Exists(CachePaths.CurrentImageBg);
            if (bgLayout.Items.Count > 0)
            {
                bgLayout.Items.Clear();
            }
            for (var i = 0; i < 5; i++)
            {
                bgLayout.Items.Add(Language.GetText($"{bgLayout.Name}Option{i}"));
            }

            intValue = (int)Settings.Window.BackgroundImageLayout;
            bgLayout.SelectedIndex = intValue > 0 && intValue < bgLayout.Items.Count ? intValue : 1;

            mainColorPanel.BackColor        = Settings.Window.Colors.Base;
            controlColorPanel.BackColor     = Settings.Window.Colors.Control;
            controlTextColorPanel.BackColor = Settings.Window.Colors.ControlText;
            btnColorPanel.BackColor         = Settings.Window.Colors.Button;
            btnHoverColorPanel.BackColor    = Settings.Window.Colors.ButtonHover;
            btnTextColorPanel.BackColor     = Settings.Window.Colors.ButtonText;

            hScrollBarCheck.Checked      = Settings.Window.HideHScrollBar;
            showLargeImagesCheck.Checked = Settings.Window.LargeImages;

            StylePreviewUpdate();

            appDirs.Text = Settings.AppDirs?.Where(x => !CorePaths.AppDirs.ContainsItem(x)).Select(x => EnvironmentEx.GetVariableWithPath(x)).Join(Environment.NewLine);

            if (startMenuIntegration.Items.Count > 0)
            {
                startMenuIntegration.Items.Clear();
            }
            for (var i = 0; i < 2; i++)
            {
                startMenuIntegration.Items.Add(Language.GetText($"{startMenuIntegration.Name}Option{i}"));
            }
            startMenuIntegration.SelectedIndex = Settings.StartMenuIntegration ? 1 : 0;

            if (defaultPos.Items.Count > 0)
            {
                defaultPos.Items.Clear();
            }
            for (var i = 0; i < 2; i++)
            {
                defaultPos.Items.Add(Language.GetText($"{defaultPos.Name}Option{i}"));
            }

            intValue = Settings.Window.DefaultPosition;
            defaultPos.SelectedIndex = intValue > 0 && intValue < defaultPos.Items.Count ? intValue : 0;
            if (updateCheck.Items.Count > 0)
            {
                updateCheck.Items.Clear();
            }
            for (var i = 0; i < 10; i++)
            {
                updateCheck.Items.Add(Language.GetText($"{updateCheck.Name}Option{i}"));
            }

            intValue = (int)Settings.UpdateCheck;
            updateCheck.SelectedIndex = intValue > 0 && intValue < updateCheck.Items.Count ? intValue : 0;
            if (updateChannel.Items.Count > 0)
            {
                updateChannel.Items.Clear();
            }
            for (var i = 0; i < 2; i++)
            {
                updateChannel.Items.Add(Language.GetText($"{updateChannel.Name}Option{i}"));
            }

            intValue = (int)Settings.UpdateChannel;
            updateChannel.SelectedIndex = intValue > 0 ? 1 : 0;

            if (!saveBtn.Focused)
            {
                saveBtn.Select();
            }
        }
예제 #29
0
        internal static void Associate(LocalAppData appData, bool quiet = false, Form owner = default)
        {
            if (appData?.Settings?.FileTypes?.Any() != true)
            {
                if (!quiet)
                {
                    MessageBoxEx.Show(owner, Language.GetText(nameof(en_US.associateBtnMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                return;
            }

            if (!Elevation.IsAdministrator)
            {
                if (owner != default)
                {
                    owner.TopMost = false;
                    owner.Enabled = false;
                    TaskBarProgress.SetState(owner.Handle, TaskBarProgressState.Indeterminate);
                }
                _bw?.Dispose();
                _bw         = new BackgroundWorker();
                _bw.DoWork += (sender, args) =>
                {
                    using (var process = ProcessEx.Start(PathEx.LocalPath, $"{ActionGuid.FileTypeAssociation} \"{appData.Key}\"", true, false))
                        if (!process?.HasExited == true)
                        {
                            process.WaitForExit();
                        }
                };
                _bw.RunWorkerCompleted += (sender, args) =>
                {
                    if (owner == default)
                    {
                        return;
                    }
                    TaskBarProgress.SetState(owner.Handle, TaskBarProgressState.NoProgress);
                    if (WinApi.NativeHelper.GetForegroundWindow() != owner.Handle)
                    {
                        WinApi.NativeHelper.SetForegroundWindow(owner.Handle);
                    }
                    owner.Enabled = true;
                    owner.TopMost = true;
                };
                _bw.RunWorkerAsync();
                return;
            }

            var assocData = new FileTypeAssocData
            {
                AppKey    = appData.Key,
                InstallId = Settings.SystemInstallId
            };

            using (var dialog = new IconBrowserDialog(Settings.IconResourcePath, Settings.Window.Colors.BaseDark, Settings.Window.Colors.ControlText, Settings.Window.Colors.Button, Settings.Window.Colors.ButtonText, Settings.Window.Colors.ButtonHover))
            {
                dialog.TopMost = true;
                dialog.Plus();
                dialog.ShowDialog();
                if (!string.IsNullOrEmpty(dialog.IconPath))
                {
                    assocData.IconPath = dialog.IconPath;
                    assocData.IconId   = dialog.IconId.ToString(CultureInfo.InvariantCulture);
                }
            }

            if (!FileEx.Exists(assocData.IconPath) || string.IsNullOrEmpty(assocData.IconId))
            {
                goto Cancel;
            }

            MessageBoxEx.ButtonText.OverrideEnabled = true;
            MessageBoxEx.ButtonText.Yes             = "App";
            MessageBoxEx.ButtonText.No     = "Launcher";
            MessageBoxEx.ButtonText.Cancel = Language.GetText(nameof(en_US.Cancel));
            var result = !quiet?MessageBoxEx.Show(Language.GetText(nameof(en_US.AssociateAppWayQuestion)), Resources.GlobalTitle, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) : DialogResult.Yes;

            switch (result)
            {
            case DialogResult.Yes:
                assocData.StarterPath = EnvironmentEx.GetVariablePathFull(appData.FilePath, false, false);
                break;

            case DialogResult.No:
                assocData.StarterPath = EnvironmentEx.GetVariablePathFull(PathEx.LocalPath, false, false);
                break;

            default:
                goto Cancel;
            }

            if (FileEx.Exists(assocData.StarterPath))
            {
                appData.Settings.FileTypeAssoc = assocData;
            }
            else
            {
                goto Cancel;
            }

            assocData = appData.Settings?.FileTypeAssoc;
            assocData?.SystemRegistryAccess?.AssociateFileTypes(false);
            return;

Cancel:
            if (!quiet)
            {
                MessageBoxEx.Show(owner, Language.GetText(nameof(en_US.OperationCanceledMsg)), MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
예제 #30
0
    static ClipboardEnabled()
    {
        var disabledText = EnvironmentEx.GetEnvironmentVariable("Verify_DisableClipboard");

        clipboardDisabled = ParseEnvironmentVariable(disabledText);
    }