Process usage refactor

This commit is contained in:
Jaex 2018-12-06 21:51:41 +03:00
parent 1b0d16ab41
commit 6d855e9ef0
16 changed files with 245 additions and 149 deletions

View file

@ -40,28 +40,32 @@ public abstract class ExternalCLIManager : IDisposable
public virtual int Open(string path, string args = null) public virtual int Open(string path, string args = null)
{ {
DebugHelper.WriteLine("CLI: \"{0}\" {1}", path, args);
if (File.Exists(path)) if (File.Exists(path))
{ {
using (process = new Process()) using (process = new Process())
{ {
ProcessStartInfo psi = new ProcessStartInfo(path); ProcessStartInfo psi = new ProcessStartInfo()
psi.UseShellExecute = false; {
psi.CreateNoWindow = true; FileName = path,
psi.RedirectStandardInput = true; WorkingDirectory = Path.GetDirectoryName(path),
psi.RedirectStandardOutput = true; Arguments = args,
psi.RedirectStandardError = true; UseShellExecute = false,
psi.Arguments = args; CreateNoWindow = true,
psi.WorkingDirectory = Path.GetDirectoryName(path); RedirectStandardInput = true,
psi.StandardOutputEncoding = Encoding.UTF8; RedirectStandardOutput = true,
psi.StandardErrorEncoding = Encoding.UTF8; RedirectStandardError = true,
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8
};
process.EnableRaisingEvents = true; process.EnableRaisingEvents = true;
if (psi.RedirectStandardOutput) process.OutputDataReceived += cli_OutputDataReceived; if (psi.RedirectStandardOutput) process.OutputDataReceived += cli_OutputDataReceived;
if (psi.RedirectStandardError) process.ErrorDataReceived += cli_ErrorDataReceived; if (psi.RedirectStandardError) process.ErrorDataReceived += cli_ErrorDataReceived;
process.StartInfo = psi; process.StartInfo = psi;
DebugHelper.WriteLine($"CLI: \"{psi.FileName}\" {psi.Arguments}");
process.Start(); process.Start();
if (psi.RedirectStandardOutput) process.BeginOutputReadLine(); if (psi.RedirectStandardOutput) process.BeginOutputReadLine();
if (psi.RedirectStandardError) process.BeginErrorReadLine(); if (psi.RedirectStandardError) process.BeginErrorReadLine();

View file

@ -71,41 +71,41 @@ public string Run(string inputPath)
{ {
string outputPath = inputPath; string outputPath = inputPath;
using (Process process = new Process()) string arguments;
if (string.IsNullOrEmpty(Args))
{ {
ProcessStartInfo psi = new ProcessStartInfo(Path); arguments = '"' + inputPath + '"';
psi.UseShellExecute = false; }
else
{
if (!string.IsNullOrWhiteSpace(OutputExtension))
{
outputPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(inputPath), System.IO.Path.GetFileNameWithoutExtension(inputPath));
if (string.IsNullOrEmpty(Args)) if (!OutputExtension.StartsWith("."))
{
psi.Arguments = '"' + inputPath + '"';
}
else
{
if (!string.IsNullOrWhiteSpace(OutputExtension))
{ {
outputPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(inputPath), System.IO.Path.GetFileNameWithoutExtension(inputPath)); outputPath += ".";
if (!OutputExtension.StartsWith("."))
{
outputPath += ".";
}
outputPath += OutputExtension;
} }
psi.Arguments = CodeMenuEntryActions.Parse(Args, inputPath, outputPath); outputPath += OutputExtension;
} }
if (HiddenWindow) arguments = CodeMenuEntryActions.Parse(Args, inputPath, outputPath);
}
using (Process process = new Process())
{
ProcessStartInfo psi = new ProcessStartInfo()
{ {
psi.CreateNoWindow = true; FileName = Path,
} Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = HiddenWindow
};
process.StartInfo = psi; process.StartInfo = psi;
DebugHelper.WriteLine($"CLI: \"{psi.FileName}\" {psi.Arguments}");
DebugHelper.WriteLine($"Running \"{psi.FileName}\" with arguments: {psi.Arguments}");
process.Start(); process.Start();
process.WaitForExit(); process.WaitForExit();
} }
@ -115,7 +115,6 @@ public string Run(string inputPath)
if (DeleteInputFile && !inputPath.Equals(outputPath, StringComparison.OrdinalIgnoreCase) && File.Exists(inputPath)) if (DeleteInputFile && !inputPath.Equals(outputPath, StringComparison.OrdinalIgnoreCase) && File.Exists(inputPath))
{ {
DebugHelper.WriteLine("Deleting input file: " + inputPath); DebugHelper.WriteLine("Deleting input file: " + inputPath);
File.Delete(inputPath); File.Delete(inputPath);
} }

View file

@ -424,7 +424,19 @@ public static bool OpenFile(string filePath)
{ {
try try
{ {
Process.Start(filePath); using (Process process = new Process())
{
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = filePath
};
process.StartInfo = psi;
process.Start();
}
DebugHelper.WriteLine("File opened: " + filePath);
return true; return true;
} }
catch (Exception e) catch (Exception e)
@ -451,7 +463,19 @@ public static bool OpenFolder(string folderPath)
try try
{ {
Process.Start(folderPath); using (Process process = new Process())
{
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = folderPath
};
process.StartInfo = psi;
process.Start();
}
DebugHelper.WriteLine("Folder opened: " + folderPath);
return true; return true;
} }
catch (Exception e) catch (Exception e)
@ -474,6 +498,9 @@ public static bool OpenFolderWithFile(string filePath)
try try
{ {
NativeMethods.OpenFolderAndSelectFile(filePath); NativeMethods.OpenFolderAndSelectFile(filePath);
DebugHelper.WriteLine("Folder opened with file: " + filePath);
return true; return true;
} }
catch (Exception e) catch (Exception e)

View file

@ -52,20 +52,29 @@ public static void OpenURL(string url)
{ {
try try
{ {
if (!string.IsNullOrEmpty(HelpersOptions.BrowserPath)) using (Process process = new Process())
{ {
Process.Start(HelpersOptions.BrowserPath, url); ProcessStartInfo psi = new ProcessStartInfo();
}
else if (!string.IsNullOrEmpty(HelpersOptions.BrowserPath))
{ {
Process.Start(url); psi.FileName = HelpersOptions.BrowserPath;
psi.Arguments = url;
}
else
{
psi.FileName = url;
}
process.StartInfo = psi;
process.Start();
} }
DebugHelper.WriteLine("URL opened: " + url); DebugHelper.WriteLine("URL opened: " + url);
} }
catch (Exception e) catch (Exception e)
{ {
DebugHelper.WriteException(e, string.Format("OpenURL({0}) failed", url)); DebugHelper.WriteException(e, $"OpenURL({url}) failed");
} }
}); });
} }

View file

@ -71,25 +71,27 @@ public bool Compress(string archivePath, List<string> files, string workingDirec
private int Run(string arguments, string workingDirectory = "") private int Run(string arguments, string workingDirectory = "")
{ {
ProcessStartInfo startInfo = new ProcessStartInfo() using (Process process = new Process())
{ {
FileName = SevenZipPath, ProcessStartInfo psi = new ProcessStartInfo()
Arguments = arguments, {
UseShellExecute = false, FileName = SevenZipPath,
CreateNoWindow = true Arguments = arguments,
}; UseShellExecute = false,
CreateNoWindow = true
};
if (!string.IsNullOrEmpty(workingDirectory)) if (!string.IsNullOrEmpty(workingDirectory))
{ {
startInfo.WorkingDirectory = workingDirectory; psi.WorkingDirectory = workingDirectory;
}
process.StartInfo = psi;
process.Start();
process.WaitForExit();
return process.ExitCode;
} }
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
return process.ExitCode;
} }
} }
} }

View file

@ -150,27 +150,32 @@ private void RunInstaller()
{ {
try try
{ {
ProcessStartInfo psi = new ProcessStartInfo(DownloadLocation) using (Process process = new Process())
{ {
Arguments = "/UPDATE" ProcessStartInfo psi = new ProcessStartInfo()
}; {
FileName = DownloadLocation,
Arguments = "/UPDATE",
UseShellExecute = false
};
if (InstallType == InstallType.Silent) if (InstallType == InstallType.Silent)
{ {
psi.Arguments += " /SILENT"; psi.Arguments += " /SILENT";
} }
else if (InstallType == InstallType.VerySilent) else if (InstallType == InstallType.VerySilent)
{ {
psi.Arguments += " /VERYSILENT"; psi.Arguments += " /VERYSILENT";
} }
if (Helpers.IsDefaultInstallDir()) if (Helpers.IsDefaultInstallDir())
{ {
psi.Verb = "runas"; psi.Verb = "runas";
} }
psi.UseShellExecute = true; process.StartInfo = psi;
Process.Start(psi); process.Start();
}
} }
catch catch
{ {

View file

@ -137,7 +137,7 @@ public void OpenDeletionURL()
public void OpenFile() public void OpenFile()
{ {
if (HistoryItem != null && IsFileExist) URLHelpers.OpenURL(HistoryItem.Filepath); if (HistoryItem != null && IsFileExist) Helpers.OpenFile(HistoryItem.Filepath);
} }
public void OpenFolder() public void OpenFolder()
@ -159,7 +159,7 @@ public void TryOpen()
} }
else if (IsFileExist) else if (IsFileExist)
{ {
URLHelpers.OpenURL(HistoryItem.Filepath); Helpers.OpenFile(HistoryItem.Filepath);
} }
} }
} }

View file

@ -76,14 +76,19 @@ public List<VideoThumbnailInfo> TakeThumbnails()
string filename = string.Format("{0}-{1}.{2}", mediaFileName, timeSliceElapsed, Options.ImageFormat.GetDescription()); string filename = string.Format("{0}-{1}.{2}", mediaFileName, timeSliceElapsed, Options.ImageFormat.GetDescription());
string tempThumbnailPath = Path.Combine(GetOutputDirectory(), filename); string tempThumbnailPath = Path.Combine(GetOutputDirectory(), filename);
using (Process p = new Process()) using (Process process = new Process())
{ {
ProcessStartInfo psi = new ProcessStartInfo(FFmpegPath); ProcessStartInfo psi = new ProcessStartInfo()
psi.WindowStyle = ProcessWindowStyle.Hidden; {
psi.Arguments = string.Format("-ss {0} -i \"{1}\" -f image2 -vframes 1 -y \"{2}\"", timeSliceElapsed, MediaPath, tempThumbnailPath); FileName = FFmpegPath,
p.StartInfo = psi; Arguments = $"-ss {timeSliceElapsed} -i \"{MediaPath}\" -f image2 -vframes 1 -y \"{tempThumbnailPath}\"",
p.Start(); UseShellExecute = false,
p.WaitForExit(1000 * 30); CreateNoWindow = true
};
process.StartInfo = psi;
process.Start();
process.WaitForExit(1000 * 30);
} }
if (File.Exists(tempThumbnailPath)) if (File.Exists(tempThumbnailPath))

View file

@ -280,9 +280,9 @@ private void cboAudioSource_SelectedIndexChanged(object sender, EventArgs e)
private async void btnInstallHelperDevices_Click(object sender, EventArgs e) private async void btnInstallHelperDevices_Click(object sender, EventArgs e)
{ {
string filepath = Helpers.GetAbsolutePath(FFmpegHelper.DeviceSetupPath); string filePath = Helpers.GetAbsolutePath(FFmpegHelper.DeviceSetupPath);
if (!string.IsNullOrEmpty(filepath) && File.Exists(filepath)) if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{ {
bool result = false; bool result = false;
@ -290,9 +290,17 @@ private async void btnInstallHelperDevices_Click(object sender, EventArgs e)
{ {
try try
{ {
Process process = Process.Start(filepath); using (Process process = new Process())
{
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = filePath
};
result = process.WaitForExit(1000 * 60 * 5) && process.ExitCode == 0; process.StartInfo = psi;
process.Start();
result = process.WaitForExit(1000 * 60 * 5) && process.ExitCode == 0;
}
} }
catch { } catch { }
}); });
@ -304,7 +312,7 @@ private async void btnInstallHelperDevices_Click(object sender, EventArgs e)
} }
else else
{ {
MessageBox.Show("File not exists: \"" + filepath + "\"", "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("File not exists: \"" + filePath + "\"", "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
@ -491,9 +499,13 @@ private void btnTest_Click(object sender, EventArgs e)
{ {
using (Process process = new Process()) using (Process process = new Process())
{ {
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe"); ProcessStartInfo psi = new ProcessStartInfo()
psi.Arguments = $"/k {Path.GetFileName(Options.FFmpeg.FFmpegPath)} {Options.GetFFmpegCommands()}"; {
psi.WorkingDirectory = Path.GetDirectoryName(Options.FFmpeg.FFmpegPath); FileName = "cmd.exe",
WorkingDirectory = Path.GetDirectoryName(Options.FFmpeg.FFmpegPath),
Arguments = $"/k {Path.GetFileName(Options.FFmpeg.FFmpegPath)} {Options.GetFFmpegCommands()}",
UseShellExecute = true
};
process.StartInfo = psi; process.StartInfo = psi;
process.Start(); process.Start();

View file

@ -173,20 +173,22 @@ private static void Main(string[] args)
if (Job.HasFlag(SetupJobs.CompileAppx)) if (Job.HasFlag(SetupJobs.CompileAppx))
{ {
Process p = new Process using (Process process = new Process())
{ {
StartInfo = new ProcessStartInfo ProcessStartInfo psi = new ProcessStartInfo()
{ {
FileName = MakeAppxPath, FileName = MakeAppxPath,
Arguments = $"pack /d \"{WindowsStoreOutputDir}\" /p \"{WindowsStoreAppxPath}\" /l /o", Arguments = $"pack /d \"{WindowsStoreOutputDir}\" /p \"{WindowsStoreAppxPath}\" /l /o",
UseShellExecute = false, UseShellExecute = false,
RedirectStandardOutput = true RedirectStandardOutput = true
} };
};
p.OutputDataReceived += (s, e) => Console.WriteLine(e.Data); process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
p.Start(); process.StartInfo = psi;
p.BeginOutputReadLine(); process.Start();
p.WaitForExit(); process.BeginOutputReadLine();
process.WaitForExit();
}
Directory.Delete(WindowsStoreOutputDir, true); Directory.Delete(WindowsStoreOutputDir, true);
} }
@ -226,11 +228,20 @@ private static void CompileISSFile(string filename)
{ {
Console.WriteLine("Compiling setup file: " + filename); Console.WriteLine("Compiling setup file: " + filename);
ProcessStartInfo startInfo = new ProcessStartInfo(InnoSetupCompilerPath, $"\"{filename}\""); using (Process process = new Process())
startInfo.UseShellExecute = false; {
startInfo.WorkingDirectory = Path.GetFullPath(InnoSetupDir); ProcessStartInfo psi = new ProcessStartInfo()
Process process = Process.Start(startInfo); {
process.WaitForExit(); FileName = InnoSetupCompilerPath,
WorkingDirectory = Path.GetFullPath(InnoSetupDir),
Arguments = $"\"{filename}\"",
UseShellExecute = false
};
process.StartInfo = psi;
process.Start();
process.WaitForExit();
}
Console.WriteLine("Setup file is created."); Console.WriteLine("Setup file is created.");
} }

View file

@ -94,15 +94,20 @@ private static void ProcessStart(string filePath, string arguments)
{ {
Console.WriteLine($"Process starting: {filePath} {arguments}"); Console.WriteLine($"Process starting: {filePath} {arguments}");
ProcessStartInfo startInfo = new ProcessStartInfo() using (Process process = new Process())
{ {
FileName = filePath, ProcessStartInfo psi = new ProcessStartInfo()
Arguments = arguments, {
UseShellExecute = false, FileName = filePath,
CreateNoWindow = true Arguments = arguments,
}; UseShellExecute = false,
CreateNoWindow = true
};
Process.Start(startInfo).WaitForExit(); process.StartInfo = psi;
process.Start();
process.WaitForExit();
}
} }
public static bool CheckArguments(string[] args, string check) public static bool CheckArguments(string[] args, string check)

View file

@ -186,14 +186,18 @@ private static void RunShareX(string arguments = "")
{ {
if (ShowInApp) if (ShowInApp)
{ {
ProcessStartInfo startInfo = new ProcessStartInfo() using (Process process = new Process())
{ {
Arguments = arguments, ProcessStartInfo psi = new ProcessStartInfo()
FileName = ContentExecutablePath, {
UseShellExecute = true FileName = ContentExecutablePath,
}; Arguments = arguments,
UseShellExecute = true
};
Process.Start(startInfo); process.StartInfo = psi;
process.Start();
}
} }
else else
{ {
@ -220,15 +224,19 @@ private static void RunShareX(string arguments = "")
path = "cmd.exe"; path = "cmd.exe";
} }
ProcessStartInfo startInfo = new ProcessStartInfo() using (Process process = new Process())
{ {
Arguments = $"/C start \"\" \"{ContentExecutablePath}\" {arguments}", ProcessStartInfo psi = new ProcessStartInfo()
CreateNoWindow = true, {
FileName = path, FileName = path,
UseShellExecute = false Arguments = $"/C start \"\" \"{ContentExecutablePath}\" {arguments}",
}; UseShellExecute = false,
CreateNoWindow = true
};
Process.Start(startInfo); process.StartInfo = psi;
process.Start();
}
} }
} }
catch (Exception e) catch (Exception e)
@ -254,10 +262,16 @@ private static void UninstallShareX()
{ {
if (File.Exists(ContentExecutablePath)) if (File.Exists(ContentExecutablePath))
{ {
Process process = Process.Start(ContentExecutablePath, "-uninstall"); using (Process process = new Process())
if (process != null)
{ {
ProcessStartInfo psi = new ProcessStartInfo()
{
FileName = ContentExecutablePath,
Arguments = "-uninstall"
};
process.StartInfo = psi;
process.Start();
process.WaitForExit(); process.WaitForExit();
} }
} }

View file

@ -176,18 +176,12 @@ private void btnOpenLink_Click(object sender, EventArgs e)
private void btnOpenFile_Click(object sender, EventArgs e) private void btnOpenFile_Click(object sender, EventArgs e)
{ {
if (!string.IsNullOrEmpty(Info.FilePath) && File.Exists(Info.FilePath)) Helpers.OpenFile(Info.FilePath);
{
URLHelpers.OpenURL(Info.FilePath);
}
} }
private void btnFolderOpen_Click(object sender, EventArgs e) private void btnFolderOpen_Click(object sender, EventArgs e)
{ {
if (!string.IsNullOrEmpty(Info.FilePath) && File.Exists(Info.FilePath)) Helpers.OpenFolderWithFile(Info.FilePath);
{
Helpers.OpenFolderWithFile(Info.FilePath);
}
} }
private void btnClose_Click(object sender, EventArgs e) private void btnClose_Click(object sender, EventArgs e)

View file

@ -238,7 +238,7 @@ private void ExecuteAction(ToastClickAction action)
break; break;
case ToastClickAction.OpenFile: case ToastClickAction.OpenFile:
if (!string.IsNullOrEmpty(ToastConfig.FilePath)) if (!string.IsNullOrEmpty(ToastConfig.FilePath))
URLHelpers.OpenURL(ToastConfig.FilePath); Helpers.OpenFile(ToastConfig.FilePath);
break; break;
case ToastClickAction.OpenFolder: case ToastClickAction.OpenFolder:
if (!string.IsNullOrEmpty(ToastConfig.FilePath)) if (!string.IsNullOrEmpty(ToastConfig.FilePath))

View file

@ -1085,10 +1085,19 @@ public static void RunShareXAsAdmin(string arguments)
{ {
try try
{ {
ProcessStartInfo psi = new ProcessStartInfo(Application.ExecutablePath); using (Process process = new Process())
psi.Arguments = arguments; {
psi.Verb = "runas"; ProcessStartInfo psi = new ProcessStartInfo()
Process.Start(psi); {
FileName = Application.ExecutablePath,
Arguments = arguments,
UseShellExecute = false,
Verb = "runas"
};
process.StartInfo = psi;
process.Start();
}
} }
catch catch
{ {

View file

@ -119,12 +119,12 @@ public void OpenDeletionURL()
public void OpenFile() public void OpenFile()
{ {
if (IsItemSelected && SelectedItem.IsFileExist) URLHelpers.OpenURL(SelectedItem.Info.FilePath); if (IsItemSelected && SelectedItem.IsFileExist) Helpers.OpenFile(SelectedItem.Info.FilePath);
} }
public void OpenThumbnailFile() public void OpenThumbnailFile()
{ {
if (IsItemSelected && SelectedItem.IsThumbnailFileExist) URLHelpers.OpenURL(SelectedItem.Info.ThumbnailFilePath); if (IsItemSelected && SelectedItem.IsThumbnailFileExist) Helpers.OpenFile(SelectedItem.Info.ThumbnailFilePath);
} }
public void OpenFolder() public void OpenFolder()
@ -146,7 +146,7 @@ public void TryOpen()
} }
else if (SelectedItem.IsFilePathValid) else if (SelectedItem.IsFilePathValid)
{ {
URLHelpers.OpenURL(SelectedItem.Info.FilePath); Helpers.OpenFile(SelectedItem.Info.FilePath);
} }
} }
} }