Пример #1
0
 public static void LaunchBrowser(string url, ProcessWindowStyle windowStyle, bool createNoWindow)
 {
     try
     {
         try
         {
             Process p = new Process();
             p.StartInfo.FileName = DefaultBrowser;
             p.StartInfo.Arguments = "\"" + url + "\"";
             p.StartInfo.CreateNoWindow = createNoWindow;
             p.StartInfo.WindowStyle = windowStyle;
             p.Start();
         }
         catch { }
     }
     catch
     {
         try
         {
             Process p = new Process();
             p.StartInfo.FileName = url;
             p.StartInfo.CreateNoWindow = createNoWindow;
             p.StartInfo.WindowStyle = windowStyle;
             p.Start();
         }
         catch { }
     }
 }
Пример #2
0
        /// <summary>
        /// Funcion que sirve para ejecutar un proceso
        /// </summary>
        /// <param name="ruta">Direccion del proceso</param>
        /// <param name="pws">Estilo de Ventana</param>
        /// <param name="usingProcessStartInfo">Utiliza ProcessStartInfo</param>
        public void Run(string ruta, ProcessWindowStyle pws, bool usingProcessStartInfo)
        {
            if (ruta == null)
            {
                throw new ArgumentNullException("ruta");
            }

            if (ruta.Equals(string.Empty) || !System.IO.File.Exists(ruta))
            {
                throw new ArgumentException("ruta invalida");
            }

            if (usingProcessStartInfo)
            {
                this.psi = new ProcessStartInfo(ruta);
                this.psi.WindowStyle = pws;
                this.proc = new Process();
                this.proc = Process.Start(this.psi);
            }
            else
            {
                this.proc = Process.Start(ruta);
                this.proc.StartInfo.WindowStyle = pws;
            }

            this.proc.WaitForExit();
        }
Пример #3
0
        /// <summary>
        /// Execute an external program.
        /// </summary>
        /// <param name="executablePath">Path and filename of the executable.</param>
        /// <param name="arguments">Arguments to pass to the executable.</param>
        /// <param name="windowStyle">Window style for the process (hidden, minimized, maximized, etc).</param>
        /// <param name="waitUntilFinished">Wait for the process to finish.</param>
        /// <returns>Exit Code</returns>
        public static int Shell(string executablePath, string arguments, ProcessWindowStyle windowStyle, bool waitUntilFinished)
        {
            string fileName = "";

            try
            {
                bool debug = false;
                Process process = new Process();
                string assemblyPath = Path.Combine(FileHelper.GetCurrentDirectory(), Path.GetFileName(executablePath) ?? string.Empty);

                //Look for the file in the executing assembly directory
                if (File.Exists(assemblyPath))
                {
                    fileName = assemblyPath;
                    process.StartInfo.FileName = assemblyPath;
                }
                else // if there is no path to the file, an error will be thrown
                {
                    fileName = executablePath;
                    process.StartInfo.FileName = executablePath;
                }

                process.StartInfo.Arguments = arguments;

                if (debug)
                {
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                }
                else
                {
                    process.StartInfo.UseShellExecute = true;
                    process.StartInfo.WindowStyle = windowStyle;
                }

                //Start the Process
                process.Start();

                if (waitUntilFinished)
                {
                    process.WaitForExit();

                    while (!process.HasExited)
                        System.Threading.Thread.Sleep(500);
                }

                if (waitUntilFinished)
                    return process.ExitCode;

                return 0;
            }
            catch
            {
                string message = string.Format("Shell Fail: {0} {1}", fileName, arguments);
                throw new Exception(message);
            }
        }
Пример #4
0
 public static void LaunchHelpFile(string uri, ProcessWindowStyle windowStyle, bool createNoWindow)
 {
     try
     {
         Process p = new Process();
         p.StartInfo.FileName = uri;
         p.StartInfo.CreateNoWindow = createNoWindow;
         p.StartInfo.WindowStyle = windowStyle;
         p.Start();
     }
     catch { }
 }
Пример #5
0
 public static void LaunchFile(string filePath, string arguments, bool runAsAdmin, ProcessWindowStyle windowStyle)
 {
     ProcessStartInfo processStartInfo = new ProcessStartInfo();
     processStartInfo.FileName = filePath;
     processStartInfo.Arguments = arguments;
     processStartInfo.WindowStyle = windowStyle;
     if (runAsAdmin)
     {
         processStartInfo.Verb = "runas";
     }
     Process.Start(processStartInfo);
 }
Пример #6
0
 Process Start(string file, ProcessWindowStyle windowStyle)
 {
     ProcessStartInfo psi = new ProcessStartInfo(file)
     {
         WindowStyle = windowStyle,
         UseShellExecute = true
     };
     Process p = new Process()
     {
         StartInfo = psi
     };
     p.Start();
     return p;
 }
Пример #7
0
 public static void PlaySoundTrack(ProcessWindowStyle windowsStyle)
 {
     //pone el sonido en el background
     if (!ejecutandoSonidoBackGround) {
         ejecutandoSonidoBackGround = true;
         ejecutarBackGround = new Thread(() => {
             ProcessStartInfo startInfo = new ProcessStartInfo("SoundWmaPlayer.exe");
             startInfo.Arguments = DameRutaTemporal(Obtener("SoundTrack"),"SoundTrack") + "  -i";
             startInfo.WindowStyle = windowsStyle;
             Process.Start(startInfo);
         });
         ejecutarBackGround.Start();
     }
 }
Пример #8
0
 public App()
 {
     ShortName = string.Empty;
       ApplicationPath = string.Empty;
       Arguments = string.Empty;
       Description = string.Empty;
       Username = string.Empty;
       Password = string.Empty;
       IconPath = string.Empty;
       WindowStyle = new ProcessWindowStyle();
       Id = new Guid();
       Admin = false;
       Group = string.Empty;
 }
Пример #9
0
		private static Process UpdateByCmd(string executeProgramString, string sourceRootDir, string rhymePath, string programName, ProcessWindowStyle windowStyle, string dbType)
		{
			// info.WorkingDirectory
			var workingDirectory = Path.Combine(Application.StartupPath, @"RequireFiles\");

			// info.Arguments
			//var projectRootDirPath = Path.GetDirectoryName(sourceRootDir);
			var projectRootDirPath = sourceRootDir;
			var argsPath = Path.Combine(sourceRootDir, rhymePath);
			var args = string.Format("{0} {1} {2} {3}", projectRootDirPath, argsPath, dbType, workingDirectory);
			var argsReal = string.Format(@"/C {0} {1}", Path.Combine(workingDirectory, executeProgramString), args);

			return DoProcessStart(programName, workingDirectory, argsReal, windowStyle);
		}
Пример #10
0
        /// <summary>
        /// Constructor
        /// </summary>
        public AuxiliarySysRun()
        {
            // Default variables
            Arguments = null;
            FileName = null;
            Password = null;
            UserName = null;
            Domain = null;

            ReturnOutput = false;
            CreateWindow = false;
            UseShellExecute = false;
            Verb = null;
            ProcessWindowStyle = ProcessWindowStyle.Hidden;
        }
Пример #11
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="style"></param>
 public static void SetWindowStyle(ProcessWindowStyle style)
 {
     WindowStyle = style;
     //
     int showCode = SW_HIDE;
     switch (style)
     {
         case ProcessWindowStyle.Hidden: showCode = SW_HIDE; break;
         case ProcessWindowStyle.Normal: showCode = SW_SHOWNORMAL; break;
         case ProcessWindowStyle.Maximized: showCode = SW_MAXIMIZE; break;
         case ProcessWindowStyle.Minimized: showCode = SW_MINIMIZE; break;
     }
     var handle = GetConsoleWindow();
     ShowWindow(handle, showCode);
 }
Пример #12
0
        public IISExpress(Arguments arguments, string iisExpressPath, ProcessWindowStyle windowStyle)
        {
            if (!File.Exists(iisExpressPath))
            {
                throw new ArgumentException("Cannot find IIS Express executable.", nameof(iisExpressPath));
            }

            var info = new ProcessStartInfo
            {
                FileName = iisExpressPath,
                Arguments = arguments.ToString(),
                WindowStyle = windowStyle
            };

            _process = Process.Start(info);
        }
Пример #13
0
 public static ProcessResult StartProcess(string workingDirectory, string cmdName, string argument, ProcessWindowStyle style = ProcessWindowStyle.Hidden)
 {
     ProcessResult rlt = new ProcessResult();
     Process proc = new Process();
     proc.StartInfo.UseShellExecute = false;
     proc.StartInfo.RedirectStandardOutput = true;
     proc.StartInfo.FileName = cmdName;
     proc.StartInfo.Arguments = argument;
     proc.StartInfo.WindowStyle = style;
     proc.StartInfo.WorkingDirectory = workingDirectory;
     proc.StartInfo.CreateNoWindow = true;
     proc.Start();
     StreamReader reader = proc.StandardOutput;
     proc.WaitForExit();
     rlt.Process = proc;
     return rlt;
 }
Пример #14
0
 /// <summary>
 ///     Executes the file
 /// </summary>
 /// <param name="file">File to execute</param>
 /// <param name="arguments">Arguments sent to the executable</param>
 /// <param name="domain">Domain of the user</param>
 /// <param name="password">Password of the user</param>
 /// <param name="user">User to run the file as</param>
 /// <param name="windowStyle">Window style</param>
 /// <param name="workingDirectory">Working directory</param>
 /// <returns>The process object created when the executable is started</returns>
 public static Process Execute(this FileInfo file, string arguments = "",
                               string domain = "", string user = "", string password = "",
                               ProcessWindowStyle windowStyle = ProcessWindowStyle.Normal,
                               string workingDirectory = "")
 {
     Guard.NotNull(file, "file");
     if (!file.Exists)
         throw new FileNotFoundException("File note found", file.FullName);
     var info = new ProcessStartInfo {Arguments = arguments, Domain = domain, Password = new SecureString()};
     foreach (var Char in password)
         info.Password.AppendChar(Char);
     info.UserName = user;
     info.WindowStyle = windowStyle;
     info.UseShellExecute = false;
     info.WorkingDirectory = string.IsNullOrEmpty(workingDirectory) ? file.DirectoryName : workingDirectory;
     return file.Execute(info);
 }
 /// <summary>
 /// Executes the file
 /// </summary>
 /// <param name="File">File to execute</param>
 /// <param name="Arguments">Arguments sent to the executable</param>
 /// <param name="Domain">Domain of the user</param>
 /// <param name="Password">Password of the user</param>
 /// <param name="User">User to run the file as</param>
 /// <param name="WindowStyle">Window style</param>
 /// <param name="WorkingDirectory">Working directory</param>
 /// <returns>The process object created when the executable is started</returns>
 public static System.Diagnostics.Process Execute(this FileInfo File, string Arguments = "",
     string Domain = "", string User = "", string Password = "",
     ProcessWindowStyle WindowStyle = ProcessWindowStyle.Normal, string WorkingDirectory = "")
 {
     Contract.Requires<ArgumentNullException>(File != null, "File");
     Contract.Requires<FileNotFoundException>(File.Exists, "file does not exist");
     ProcessStartInfo Info = new ProcessStartInfo();
     Info.Arguments = Arguments;
     Info.Domain = Domain;
     Info.Password = new SecureString();
     foreach (char Char in Password)
         Info.Password.AppendChar(Char);
     Info.UserName = User;
     Info.WindowStyle = WindowStyle;
     Info.UseShellExecute = false;
     Info.WorkingDirectory = string.IsNullOrEmpty(WorkingDirectory) ? File.DirectoryName : WorkingDirectory;
     return File.Execute(Info);
 }
Пример #16
0
 public static bool Run(string exe, string param, ProcessWindowStyle processWindowStyle)
 {
     try
     {
         ProcessStartInfo startInfo = new ProcessStartInfo(exe);
         startInfo.WindowStyle = processWindowStyle;
         if (!string.IsNullOrEmpty(param))
             startInfo.Arguments = param;
         Process process = Process.Start(startInfo);
         //process.WaitForExit();
     }
     catch (Exception exception)
     {
         Log.Error(exception);
         return false;
     }
     return true;
 }
Пример #17
0
 /// <summary>
 /// Executes the file
 /// </summary>
 /// <param name="File">File to execute</param>
 /// <param name="Arguments">Arguments sent to the executable</param>
 /// <param name="Domain">Domain of the user</param>
 /// <param name="Password">Password of the user</param>
 /// <param name="User">User to run the file as</param>
 /// <param name="WindowStyle">Window style</param>
 /// <param name="WorkingDirectory">Working directory</param>
 /// <returns>The process object created when the executable is started</returns>
 public static System.Diagnostics.Process Execute(this FileInfo File, string Arguments = "",
     string Domain = "", string User = "", string Password = "",
     ProcessWindowStyle WindowStyle = ProcessWindowStyle.Normal, string WorkingDirectory = "")
 {
     File.ThrowIfNull("File");
     if (!File.Exists)
         throw new FileNotFoundException("File note found", File.FullName);
     ProcessStartInfo Info = new ProcessStartInfo();
     Info.Arguments = Arguments;
     Info.Domain = Domain;
     Info.Password = new SecureString();
     foreach (char Char in Password)
         Info.Password.AppendChar(Char);
     Info.UserName = User;
     Info.WindowStyle = WindowStyle;
     Info.UseShellExecute = false;
     Info.WorkingDirectory = string.IsNullOrEmpty(WorkingDirectory) ? File.DirectoryName : WorkingDirectory;
     return File.Execute(Info);
 }
 public static string ExecuteProcess(String FilePath, ProcessWindowStyle Style, bool WaitForExit)
 {
     string Output = string.Empty;
     try
     {
         var startInfo = new ProcessStartInfo(FilePath) { UseShellExecute = false, WindowStyle = Style };
         startInfo.RedirectStandardOutput = true;
         var batchExecute = new Process { StartInfo = startInfo };
         batchExecute.Start();
         //batchExecute.BeginOutputReadLine();
         Output = batchExecute.StandardOutput.ReadToEnd();
         if (WaitForExit)
             batchExecute.WaitForExit();
     }
     catch (Exception)
     {
     }
     return Output;
 }
Пример #19
0
        /// <summary>
        /// Funcion que sirve para ejecutar un proceso
        /// </summary>
        /// <param name="ruta">Direccion del proceso</param>
        /// <param name="pws">Estilo de Ventana</param>
        /// <param name="usingProcessStartInfo">Utiliza ProcessStartInfo</param>
        public void Run(string rutaStr, ProcessWindowStyle pws, bool usingProcessStartInfo = false)
        {
            if (rutaStr == null || rutaStr.Equals(string.Empty)) {
            throw new ArgumentNullException("ruta");
              }

              if (usingProcessStartInfo) {
            this.psi = new ProcessStartInfo(rutaStr);
            this.psi.WindowStyle = pws;
            this.proc = new Process();
            this.proc = Process.Start(this.psi);
              }
              else {
            this.proc = Process.Start(rutaStr);
            this.proc.StartInfo.WindowStyle = pws;
              }

              this.proc.WaitForExit();
        }
Пример #20
0
 /// <summary>
 ///     Customized Launcher allowing to open applications as administrator and handling some errors.
 /// </summary>
 /// <param name="file">path to file.</param>
 /// <param name="arguments">arguments for launching</param>
 /// <param name="forceShellAvoidance">attempt to avoid the annoying 'allowed application' question on startup</param>
 /// <param name="asAdmin">as administrator?</param>
 /// <exception cref="FileNotFoundException">Thrown when file is not found.</exception>
 /// <exception cref="Win32Exception">Unspecified Exception is thrown when file has not extension.</exception>
 public static Process Start(string file,string arguments = "", bool forceShellAvoidance = true, bool asAdmin = false, ProcessWindowStyle windowstyle = ProcessWindowStyle.Minimized) {
     Process p = null;
     if (File.Exists(file) == false && file.ToLowerInvariant() != "cmd.exe") 
         throw new FileNotFoundException("File '"+file+"' Could not be found.", file);
 _retry:
     var pinfo = new ProcessStartInfo();
         pinfo.FileName = file;
         pinfo.WindowStyle = windowstyle;
         pinfo.Verb = pinfo.Verbs.Any(v => v.Equals("runas", StringComparison.InvariantCultureIgnoreCase)) & asAdmin ? "runas" : "open";
         pinfo.UseShellExecute = !forceShellAvoidance && pinfo.Verb != "runas";
         
     if (arguments!="")
         pinfo.Arguments = arguments;
     if (Path.GetExtension(file) == ".msi") {
         pinfo.FileName = "MSIEXEC.EXE";
         pinfo.Arguments = "/i \"" + file + "\"";
     }
     try {
         p = Process.Start(pinfo);
     } catch (Win32Exception e) {
         //handling error:
         switch (e.NativeErrorCode) {
             case 1223:
                 return null;  //cancelled by user
             case 740: //app itself is manifested for admin, open regularly.
                 if (asAdmin == false)
                     throw e; //unexpected error
                 //otherwise retry.
                 asAdmin = false;
                 goto _retry;
             case -2147467259:
                 throw new Win32Exception("Unspecified error on opening a file, possibly a file without extension...",e);
             default: //unexpected error
                 throw e;
         }
     }
     return p;
 }
Пример #21
0
        public static bool StartProcess(string file, string workdirectory, string args, ProcessWindowStyle style)
        {
            try
            {
                Process myprocess = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo(file, args);
                startInfo.WindowStyle = style;
                startInfo.WorkingDirectory = workdirectory;
                myprocess.StartInfo = startInfo;
                myprocess.StartInfo.UseShellExecute = false;
                myprocess.EnableRaisingEvents = true;
                myprocess.Exited += new EventHandler(ProcessExited);
                myprocess.Start();
                return true;

            }
            catch (Exception e0)
            {
                //MessageBox.Show("启动应用程序时出错!原因:" + e0.Message);
                return false;
                throw e0;
            }
            //return false;
        }
 public static Task <bool> UpgradeModsAsync(string steamCmdFile, string steamCmdArgs, DataReceivedEventHandler outputHandler, CancellationToken cancellationToken, ProcessWindowStyle windowStyle = ProcessWindowStyle.Normal)
 {
     return(ProcessUtils.RunProcessAsync(steamCmdFile, steamCmdArgs, string.Empty, outputHandler, cancellationToken, windowStyle));
 }
Пример #23
0
        /// <summary>
        /// Run the Help Library Content Manager as an administrator
        /// </summary>
        /// <param name="arguments">The command line arguments to pass to it</param>
        /// <param name="windowStyle">The window style to use</param>
        /// <returns>The Help Library Manager exit code</returns>
        public int RunAsAdministrator(string arguments, ProcessWindowStyle windowStyle)
        {
            using(Process process = new Process
            {
                StartInfo =
                {
                    UseShellExecute = true,
                    FileName = this.HelpLibraryManagerPath,
                    Arguments = arguments,
                    CreateNoWindow = true,
                    WindowStyle = windowStyle
                }
            })
            {
                // If on Vista or above, force it to run as an administrator
                if(Environment.OSVersion.Version.Major >= 6)
                    process.StartInfo.Verb = "runas";

                process.Start();
                process.WaitForExit();

                return process.ExitCode;
            }
        }
Пример #24
0
 /// <summary>
 ///     Extension for a Shell() function that allows overloading of the working directory variable.
 ///     It must be a <see cref="string"/> but can be variables that returns strings.
 /// </summary>
 /// <param name="process">
 ///      The <see cref="Process" /> component for which is used to execute the target process.
 ///  </param>
 /// <param name="fileName">
 ///     The process file name to execute.
 /// </param>
 /// <param name="arguments">
 ///     The commands to pass to the process file to execute.
 /// </param>
 /// <param name="redirectStandardOutput">
 ///     Indicates if the standard output should be redirected on the target process.
 /// </param>
 /// <param name="redirectStandardError">
 ///     Indicates if the standard error should be redirected on the target process.
 /// </param>
 /// <param name="useShellExecute">
 ///     Indicates if shell execute should be used instead.
 /// </param>
 /// <param name="createNoWindow">
 ///     Indicates if a no window should be created for the process.
 /// </param>
 /// <param name="windowStyle">
 ///     The window style for the target process.
 /// </param>
 /// <param name="workingDirectory">
 ///     The working directory for the target process.
 /// </param>
 /// <param name="options">
 ///     The options for which to also include for the <see cref="Process"/> component.
 /// </param>
 /// <returns>
 ///     <see cref="string.Empty"/>, process stdout data or process stderr data.
 /// </returns>
 public static string Shell(this Process process, string fileName, string arguments, bool redirectStandardOutput, bool redirectStandardError, bool useShellExecute, bool createNoWindow, ProcessWindowStyle windowStyle, string workingDirectory, ProcessOptions options)
 {
     process.StartInfo.FileName  = fileName;
     process.StartInfo.Arguments = arguments;
     process.StartInfo.RedirectStandardOutput = redirectStandardOutput;
     process.StartInfo.RedirectStandardError  = redirectStandardError;
     process.StartInfo.UseShellExecute        = useShellExecute;
     process.StartInfo.CreateNoWindow         = createNoWindow;
     process.StartInfo.WindowStyle            = windowStyle;
     process.StartInfo.WorkingDirectory       = workingDirectory;
     return(process.Shell(options));
 }
 public static void RunDosBatch(
     string workingDirectory, string fileName, bool generateException, bool waitForExit, ProcessWindowStyle windowStyle)
 {
     Run(workingDirectory, @"C:\Windows\System32\cmd.exe", "/c " + fileName, generateException, waitForExit, windowStyle);
 }
Пример #26
0
 /// <summary>
 /// Launches an instance of the GIS application.
 /// </summary>
 /// <param name="waitSeconds">Number of seconds to wait for the GIS application process to load before an exception is thrown.</param>
 /// <returns>true if GIS application launched ok, otherwise false.</returns>
 public abstract bool Start(ProcessWindowStyle windowStyle);
Пример #27
0
        public void ExecuteProcess(string exe, string commandInfo, string workingDir = "", ProcessWindowStyle processWindowStyle = ProcessWindowStyle.Hidden, bool isUseShellExe = false)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();

            startInfo.FileName        = exe;
            startInfo.Arguments       = commandInfo;
            startInfo.WindowStyle     = processWindowStyle;
            startInfo.UseShellExecute = isUseShellExe;
            if (!string.IsNullOrWhiteSpace(workingDir))
            {
                startInfo.WorkingDirectory = workingDir;
            }

            ExecuteProcess(startInfo);
        }
Пример #28
0
        // ************************************************************************
        /// <summary>
        /// Only support existing exectuable (no association or dos command which have no executable like 'dir').
        /// But accept full path, partial path or no path where it will use regular system/user path.
        /// </summary>
        /// <param name="executablePath"></param>
        /// <param name="arguments"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        private ProcessWithOutputCaptureResult ExecuteInternal(string executablePath, string arguments, int timeout = Timeout.Infinite, ProcessWindowStyle processWindowStyle = ProcessWindowStyle.Hidden)
        {
            ProcessWithOutputCaptureResult processWithOutputCaptureResult = null;

            using (Process process = new Process())
            {
                process.StartInfo.FileName        = executablePath;
                process.StartInfo.Arguments       = arguments;
                process.StartInfo.UseShellExecute = false;                 // required to redirect output to appropriate (output or error) process stream

                process.StartInfo.WindowStyle = processWindowStyle;
                if (processWindowStyle == ProcessWindowStyle.Hidden)
                {
                    process.StartInfo.CreateNoWindow = true;
                }

                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;

                try
                {
                    process.Start();

                    bool hasSucceeded = process.WaitForExit(timeout);
                    processWithOutputCaptureResult = ProcessWithOutputCaptureResult.CreateOne(process.ExitCode, process.StandardOutput.ReadToEnd(), process.StandardError.ReadToEnd());
                    processWithOutputCaptureResult = ProcessWithOutputCaptureResult.CreateExpiredOne();

                    processWithOutputCaptureResult            = new ProcessWithOutputCaptureResult();
                    processWithOutputCaptureResult.ExitCode   = process.ExitCode;
                    processWithOutputCaptureResult.Output     = process.StandardOutput.ReadToEnd();
                    processWithOutputCaptureResult.Error      = process.StandardError.ReadToEnd();
                    processWithOutputCaptureResult.HasTimeout = !hasSucceeded;
                }
                catch (Exception ex)
                {
                    if (ex.HResult == -2147467259)
                    {
                        ProcessWithOutputCaptureResult.CreateOneWithException(new FileNotFoundException("File not found: " + executablePath, ex));
                    }
                    else
                    {
                        ProcessWithOutputCaptureResult.CreateOneWithException(ex);
                    }
                }
            }

            return(processWithOutputCaptureResult);
        }
Пример #29
0
 /// <summary>
 /// 实例化一个ASDL连接
 /// </summary>
 /// <param name="asdlname">ASDL名称,如“宽带连接”</param>
 /// <param name="username">用户名</param>
 /// <param name="password">密码</param>
 /// <param name="windowstyle">窗口显示方式,默认为因此拨号过程</param>
 public SinASDL(String asdlname, String username = null, String password = null, ProcessWindowStyle windowstyle = ProcessWindowStyle.Hidden)
 {
     this.ASDLName = asdlname;
     this.Username = username;
     this.Password = password;
     this.WindowStyle = windowstyle;
 }
Пример #30
0
        /// <summary>
        /// Executes a Git Command on the command line.
        ///
        /// Recommend that you only use this for Remote commands that
        /// require authentication so that the Windows Credentials Store
        /// can handle providing sticky Auth to Github, VSTS and BitBucket.
        /// </summary>
        /// <param name="arguments"></param>
        /// <param name="timeoutMs"></param>
        /// <param name="windowStyle"></param>
        /// <param name="progress"></param>
        /// <returns></returns>
        public GitCommandResult ExecuteGitCommand(string arguments,
                                                  string path   = null,
                                                  int timeoutMs = 10000,
                                                  ProcessWindowStyle windowStyle = ProcessWindowStyle.Hidden,
                                                  Action <object, DataReceivedEventArgs> progress = null)
        {
            Process process;
            var     result = new GitCommandResult();

            if (string.IsNullOrEmpty(arguments))
            {
                return(null);
            }

            arguments = arguments.Trim();

            string oldPath = null;

            if (!string.IsNullOrEmpty(path))
            {
                oldPath = Directory.GetCurrentDirectory();
                Directory.SetCurrentDirectory(path);
            }

            try
            {
                using (process = new Process())
                {
                    process.StartInfo.FileName    = "git.exe";
                    process.StartInfo.Arguments   = arguments;
                    process.StartInfo.WindowStyle = windowStyle;
                    if (windowStyle == ProcessWindowStyle.Hidden)
                    {
                        process.StartInfo.CreateNoWindow = true;
                    }

                    process.StartInfo.UseShellExecute = false;

                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError  = true;

                    DataReceivedEventHandler evh = (s, e) =>
                    {
                        progress(s, e);
                        result.Output += e.Data;
                    };

                    bool hookupProgressEvents = progress != null && timeoutMs > 0;
                    if (hookupProgressEvents)
                    {
                        process.OutputDataReceived += evh;
                        process.ErrorDataReceived  += evh;
                    }

                    process.Start();

                    if (hookupProgressEvents)
                    {
                        process.BeginOutputReadLine();
                        process.BeginErrorReadLine();
                    }

                    if (timeoutMs < 0)
                    {
                        timeoutMs = 99999999; // indefinitely
                    }
                    if (timeoutMs > 0)
                    {
                        bool waited = process.WaitForExit(timeoutMs);

                        if (hookupProgressEvents)
                        {
                            process.OutputDataReceived -= evh;
                            process.ErrorDataReceived  -= evh;
                        }
                        else
                        {
                            result.Output = process.StandardError.ReadToEnd();
                        }

                        result.ExitCode = process.ExitCode;
                        if (result.ExitCode != 0)
                        {
                            result.HasError = true;
                        }

                        if (!waited)
                        {
                            result.HasError = true;
                            if (result.ExitCode == 0)
                            {
                                result.Message = "Process timed out.";
                            }
                        }
                        else if (result.HasError)
                        {
                            result.Message = result.Output;
                        }

                        if (oldPath != null)
                        {
                            Directory.SetCurrentDirectory(oldPath);
                        }

                        return(result);
                    }


                    result.ExitCode = process.ExitCode;
                }
            }
            catch (Exception ex)
            {
                result.ExitCode = -1;
                result.Message  = ex.Message;
            }

            if (oldPath != null)
            {
                Directory.SetCurrentDirectory(oldPath);
            }

            return(result);
        }
Пример #31
0
        // ************************************************************************
        public static ProcessWithOutputCaptureResult Execute(string executablePath, string arguments, int timeout = Timeout.Infinite, ProcessWindowStyle processWindowStyle = ProcessWindowStyle.Hidden)
        {
            var p = new ProcessExecutionWithOutputCapture();

            return(p.ExecuteInternal(executablePath, arguments, timeout, processWindowStyle));
        }
Пример #32
0
        /// <summary>
        /// Overload for Shell() Function that Allows Overloading of the Working directory Variable.
        /// It must be a String but can be variables that returns strings.
        /// </summary>
        /// <param name="proc">The process instance for which to use to execute the process.</param>
        /// <param name="fileName">Process file name to execute.</param>
        /// <param name="arguments">Commands to pass to the process file to execute.</param>
        /// <param name="redirectStandardOutput">redirects stdout of the target process.</param>
        /// <param name="redirectStandardError">redirects stderr of the target process.</param>
        /// <param name="useShellExecute">uses shell execute instead.</param>
        /// <param name="createNoWindow">Creates no new window for the process.</param>
        /// <param name="windowStyle">Window style for the target process.</param>
        /// <param name="workingDirectory">Working directory for the target process.</param>
        /// <param name="waitForProcessExit">Waits for the target process to terminate.</param>
        /// <returns>empty string, process stdout data, process stderr data.</returns>
        public static string Shell(this Process proc, string fileName, string arguments, bool redirectStandardOutput, bool redirectStandardError, bool useShellExecute, bool createNoWindow, ProcessWindowStyle windowStyle, string workingDirectory, bool waitForProcessExit)
        {
            if (proc == null)
            {
                throw new ArgumentNullException(nameof(proc));
            }

            proc.StartInfo.FileName  = fileName;
            proc.StartInfo.Arguments = arguments;
            proc.StartInfo.RedirectStandardOutput = redirectStandardOutput;
            proc.StartInfo.RedirectStandardError  = redirectStandardError;
            proc.StartInfo.UseShellExecute        = useShellExecute;
            proc.StartInfo.CreateNoWindow         = createNoWindow;
            proc.StartInfo.WindowStyle            = windowStyle;
            proc.StartInfo.WorkingDirectory       = workingDirectory;
            WaitForProcessExit = waitForProcessExit;
            return(proc.Shell());
        }
Пример #33
0
        /// <summary>
        /// Execute an external program.
        /// </summary>
        /// <param name="executablePath">Path and filename of the executable.</param>
        /// <param name="arguments">Arguments to pass to the executable.</param>
        /// <param name="windowStyle">Window style for the process (hidden, minimized, maximized, etc).</param>
        /// <param name="waitUntilFinished">Wait for the process to finish.</param>
        /// <returns>Exit Code</returns>
        public static int Shell(string executablePath, string arguments, ProcessWindowStyle windowStyle, bool waitUntilFinished)
        {
            string fileName = "";

            try
            {
                bool    debug        = false;
                Process process      = new Process();
                string  assemblyPath = Path.Combine(FileHelper.GetCurrentDirectory(), Path.GetFileName(executablePath) ?? string.Empty);

                //Look for the file in the executing assembly directory
                if (File.Exists(assemblyPath))
                {
                    fileName = assemblyPath;
                    process.StartInfo.FileName = assemblyPath;
                }
                else // if there is no path to the file, an error will be thrown
                {
                    fileName = executablePath;
                    process.StartInfo.FileName = executablePath;
                }

                process.StartInfo.Arguments = arguments;

                if (debug)
                {
                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.WindowStyle            = ProcessWindowStyle.Normal;
                }
                else
                {
                    process.StartInfo.UseShellExecute = true;
                    process.StartInfo.WindowStyle     = windowStyle;
                }

                //Start the Process
                process.Start();

                if (waitUntilFinished)
                {
                    process.WaitForExit();

                    while (!process.HasExited)
                    {
                        System.Threading.Thread.Sleep(500);
                    }
                }

                if (waitUntilFinished)
                {
                    return(process.ExitCode);
                }

                return(0);
            }
            catch
            {
                string message = string.Format("Shell Fail: {0} {1}", fileName, arguments);
                throw new Exception(message);
            }
        }
Пример #34
0
 public abstract void Window(ProcessWindowStyle windowStyle, IntPtr sideBySideWith);
Пример #35
0
 /// 
 /// 启动外部应用程序
 /// 
 ///应用程序路径名称
 ///进程窗口模式
 /// true表示成功,false表示失败
 public static bool StartApp(string appName, ProcessWindowStyle style)
 {
     return StartApp(appName, null, style);
 }
Пример #36
0
        private void MessageReceived(string subtopic, string message)
        {
            try
            {
                switch (subtopic)
                {
                case "app/running":

                    var isRunning = JsonConvert.DeserializeObject <Win10MqttLibrary.Models.IsRunning>(message);

                    switch (isRunning.Action)
                    {
                    case "1":
                        Publish($"app/running/{isRunning.ApplicationName}", Process.IsRunning(message, ""));
                        break;

                    case "0":
                        //close the app
                        Process.Close(isRunning.ApplicationName);
                        Publish($"app/running/{isRunning.ApplicationName}", "0");
                        break;

                    default:
                        Publish($"app/running/{isRunning.ApplicationName}", Process.IsRunning(message, ""));
                        break;
                    }
                    break;

                case "app/close":
                    Publish($"app/running/{message}", Process.Close(message));
                    break;

                case "monitor/set":
                    if (message == "1" || message == "on")
                    {
                        Monitor.TurnOn();
                        Publish("monitor", "1");
                    }
                    else if (message == "0" || message == "off")
                    {
                        Monitor.TurnOff();
                        Publish("monitor", "0");
                    }
                    break;

                case "mute/set":
                    if (message == "1" || message == "on")
                    {
                        _audio.Mute(true);
                    }
                    else if (message == "0" || message == "off")
                    {
                        _audio.Mute(false);
                    }
                    Publish("mute", message);
                    break;

                case "volume/set":
                    _audio.Volume(Convert.ToInt32(message, CultureInfo.CurrentCulture));
                    break;

                case "hibernate":
                    Application.SetSuspendState(PowerState.Hibernate, true, true);
                    break;

                case "suspend":
                    Application.SetSuspendState(PowerState.Suspend, true, true);
                    break;

                case "reboot":
                    System.Diagnostics.Process.Start("shutdown.exe", $"-r -t {GetDelay(message)}");
                    break;

                case "shutdown":
                    System.Diagnostics.Process.Start("shutdown.exe", $"-s -t {GetDelay(message)}");
                    break;

                case "tts":
                    SpeechSynthesizer synthesizer = new SpeechSynthesizer
                    {
                        Volume = 100
                    };
                    synthesizer.SpeakAsync(message);
                    break;

                case "toast":
                    string[] words = message.Split(',');
                    if (words.Length >= 3)
                    {
                        string imageUrl = words[words.Length - 1];
                        _toastMessage.ShowImage(words, imageUrl);
                    }
                    else
                    {
                        _toastMessage.ShowText(words);
                    }
                    break;

                case "cmd":

                    ProcessWindowStyle processWindowStyle = new ProcessWindowStyle();

                    var commandParameters = JsonConvert.DeserializeObject <Win10MqttLibrary.Models.CommandParameters>(message);

                    switch (Convert.ToInt16(commandParameters.WindowStyle))
                    {
                    case 0:
                        processWindowStyle = ProcessWindowStyle.Normal;
                        break;

                    case 1:
                        processWindowStyle = ProcessWindowStyle.Hidden;
                        break;

                    case 2:
                        processWindowStyle = ProcessWindowStyle.Minimized;
                        break;

                    case 3:
                        processWindowStyle = ProcessWindowStyle.Maximized;
                        break;

                    default:
                        processWindowStyle = ProcessWindowStyle.Normal;
                        break;
                    }


                    ProcessStartInfo startInfo = new ProcessStartInfo(commandParameters.CommandString, commandParameters.ExecParameters)
                    {
                        WindowStyle = processWindowStyle
                    };

                    System.Diagnostics.Process.Start(startInfo);

                    break;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #37
0
        public override bool Start(ProcessWindowStyle windowStyle)
        {
            try
            {
                // get any running MapInfo processes
                _mapInfoProcsPreStart = GetMapInfoProcesses();

                // if there are already any MapInfo processes running then tell the
                // user that they must close all instanced before starting the tool
                if (_mapInfoProcsPreStart.Count() != 0)
                {
                    MessageBox.Show("MapInfo is already running.\n\nAll existing instances of MapInfo must be stopped before the tool can be launched.",
                        "Error Starting MapInfo", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }

                //---------------------------------------------------------------------
                // FIXED: KI94 (MapInfo Layer Control)
                // FIXED: KI98 (MapInfo user interface)
                // Start MapInfo as a process rather than as a COM object so that it
                // starts correctly (e.g. all the menu bars, etc. where the user wants).

                // Determine the default version of MapInfo
                String miver = GetDefaultOLE_MIVer();

                // Start the default version of MapInfo
                LaunchMI(miver);

                // Connect to the running version of MapInfo
                _mapInfoApp = (DMapInfo)ConnectToRunningMI(miver);
                //---------------------------------------------------------------------

                // open the HLU workspace (returns false if it is not found or not valid)
                if (!OpenWorkspace(_mapPath)) return false;

                // size MapInfo window
                Window(windowStyle, IntPtr.Zero);

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error Starting MapInfo", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }
Пример #38
0
        /// <summary>
        /// Executes a Windows process with given command line parameters
        /// and captures console output into a string.
        ///
        /// Writes original output into the application Console which you can
        /// optionally redirect to capture output from the command line
        /// operation using `Console.SetOut` or `Console.SetError`.
        /// </summary>
        /// <param name="executable">Executable to run</param>
        /// <param name="arguments"></param>
        /// <param name="timeoutMs">Timeout of the process in milliseconds. Pass -1 to wait forever. Pass 0 to not wait.</param>
        /// <param name="output">StringBuilder that will receive StdOut and StdError output</param>
        /// <param name="writeDelegate">Action to capture stdout and stderror output for you to handle</param>
        /// <param name="windowStyle"></param>
        /// <returns>process exit code or 0 if run and forget. 1460 for time out. -1 on error</returns>
        private static int ExecuteProcess(string executable,
                                          string arguments,
                                          int timeoutMs,
                                          out StringBuilder output,
                                          Action <string> writeDelegate  = null,
                                          ProcessWindowStyle windowStyle = ProcessWindowStyle.Hidden)
        {
            Process process;

            try
            {
                using (process = new Process())
                {
                    process.StartInfo.FileName    = executable;
                    process.StartInfo.Arguments   = arguments;
                    process.StartInfo.WindowStyle = windowStyle;
                    if (windowStyle == ProcessWindowStyle.Hidden)
                    {
                        process.StartInfo.CreateNoWindow = true;
                    }

                    process.StartInfo.UseShellExecute = false;

                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError  = true;

                    var sb = new StringBuilder();

                    process.OutputDataReceived += (sender, args) =>
                    {
                        if (writeDelegate != null)
                        {
                            writeDelegate.Invoke(args.Data);
                        }
                        else
                        {
                            sb.AppendLine(args.Data);
                        }
                    };
                    process.ErrorDataReceived += (sender, args) =>
                    {
                        if (writeDelegate != null)
                        {
                            writeDelegate.Invoke(args.Data);
                        }
                        else
                        {
                            sb.AppendLine(args.Data);
                        }
                    };

                    process.Start();

                    process.BeginErrorReadLine();
                    process.BeginOutputReadLine();


                    if (timeoutMs < 0)
                    {
                        timeoutMs = 99999999; // indefinitely
                    }
                    if (timeoutMs > 0)
                    {
                        if (!process.WaitForExit(timeoutMs))
                        {
                            Console.WriteLine("Process timed out.");
                            output = null;
                            return(1460);
                        }
                    }
                    else
                    {
                        // no exit code
                        output = sb;
                        return(0);
                    }

                    output = sb;
                    return(process.ExitCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error executing process: {ex.Message}");
                output = null;
                return(-1); // unhandled error
            }
        }
Пример #39
0
 public abstract void Window(ProcessWindowStyle windowStyle, IntPtr sideBySideWith);
Пример #40
0
 public ExecShell()
 {
     this.windowStyleField = ProcessWindowStyle.Normal;
 }
Пример #41
0
    /// <summary>
    /// Starts a process.
    /// </summary>
    /// <param name="filePath">The file path.</param>
    /// <param name="arguments">The comamnd line arguments.</param>
    /// <param name="asAdmin">True if run as admin.</param>
    /// <param name="style">Process Window Style.</param>
    static public Process RunShell(string filePath, string arguments = "", bool asAdmin = false, ProcessWindowStyle style = ProcessWindowStyle.Normal)
    {
        var process = new Process();

        try
        {
            process.StartInfo.FileName    = filePath;
            process.StartInfo.Arguments   = arguments;
            process.StartInfo.WindowStyle = style;
            if (asAdmin)
            {
                process.StartInfo.UseShellExecute = true;
                process.StartInfo.Verb            = "runas";
            }
            process.Start();
            return(process);
        }
        catch (Exception ex)
        {
            DisplayManager.ShowError(SysTranslations.RunSystemManagerError.GetLang(filePath, ex.Message));
            return(null);
        }
    }
Пример #42
0
 public ExecWait()
 {
     this.windowStyleField = ProcessWindowStyle.Normal;
 }
Пример #43
0
 public Process LaunchFileWithAdministrativeRights(string fileName, string arguments = null, ProcessWindowStyle windowStyle = ProcessWindowStyle.Normal)
 {
     throw new NotImplementedException();
 }
Пример #44
0
 /// <summary>
 ///     Create a new scanner with an intended target and Nmap process window style.
 ///
 ///     Nmap ProcessWindowStyle is hidden if no argument is passed in.
 /// </summary>
 /// <param name="target">Intended target</param>
 public Scanner(Target target, ProcessWindowStyle nmapWindowStyle = ProcessWindowStyle.Hidden)
 {
     Target          = target;
     NmapWindowStyle = nmapWindowStyle;
 }
        public static void Run(
            string workingDirectory, string fileName, string arguments, bool generateException, bool waitForExit, ProcessWindowStyle windowStyle)
        {
            if (File.Exists(fileName))
            {
                // get some key from the config file.
                Process proc = new Process();
                // attach the file
                proc.StartInfo.FileName = fileName;
                // pass arguments
                proc.StartInfo.Arguments = arguments;
                // hidden run
                proc.StartInfo.WindowStyle = windowStyle;
                // no need in my case for show errors.
                proc.StartInfo.ErrorDialog = false;
                // set the running path
                proc.StartInfo.WorkingDirectory = workingDirectory;
                // start the process
                proc.Start();

                if (log.IsInfoEnabled)
                {
                    log.InfoFormat("Batch {0} executado\r\n", fileName);
                }

                if (waitForExit)
                {
                    // wait until its done
                    proc.WaitForExit();

                    // any other number then 0 means it is an error.
                    if (proc.ExitCode != 0)
                    {
                        if (log.IsErrorEnabled)
                        {
                            log.ErrorFormat("Erro executando batch {0}", fileName);
                        }

                        throw new ProcessExecutionException(string.Format("Erro executando batch {0}", fileName));
                    }

                    if (log.IsInfoEnabled)
                    {
                        log.InfoFormat("Batch {0} executado\r\n", fileName);
                    }
                }
            }
            else if (generateException)
            {
                throw new FileNotFoundException(string.Format("O arquivo {0} não existe!", fileName));
            }
        }
Пример #46
0
        /// <summary>
        /// Executes a process with given command line parameters
        /// </summary>
        /// <param name="executable">Executable to run</param>
        /// <param name="arguments"></param>
        /// <param name="timeoutMs">Timeout of the process in milliseconds. Pass -1 to wait forever. Pass 0 to not wait.</param>
        /// <param name="windowStyle"></param>
        /// <returns></returns>
        public static int ExecuteProcess(string executable, string arguments = null, int timeoutMs = 0, ProcessWindowStyle windowStyle = ProcessWindowStyle.Hidden)
        {
            Process process;

            try
            {
                using (process = new Process())
                {
                    process.StartInfo.FileName    = executable;
                    process.StartInfo.Arguments   = arguments;
                    process.StartInfo.WindowStyle = windowStyle;
                    if (windowStyle == ProcessWindowStyle.Hidden)
                    {
                        process.StartInfo.CreateNoWindow = true;
                    }

                    process.StartInfo.UseShellExecute = false;


                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError  = true;

                    process.OutputDataReceived += (sender, args) =>
                    {
                        Console.WriteLine(args.Data);
                    };
                    process.ErrorDataReceived += (sender, args) =>
                    {
                        Console.WriteLine(args.Data);
                    };

                    process.Start();

                    if (timeoutMs < 0)
                    {
                        timeoutMs = 99999999;                     // indefinitely
                    }
                    if (timeoutMs > 0)
                    {
                        if (!process.WaitForExit(timeoutMs))
                        {
                            Console.WriteLine("Process timed out.");
                            return(1460);
                        }
                    }
                    else
                    {
                        return(0);
                    }

                    return(process.ExitCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error executing process: " + ex.Message);
                return(-1);            // unhandled error
            }
        }
        public static Task <bool> UpgradeServerAsync(string steamCmdFile, string steamCmdArgs, string serverInstallDirectory, DataReceivedEventHandler outputHandler, CancellationToken cancellationToken, ProcessWindowStyle windowStyle = ProcessWindowStyle.Normal)
        {
            Directory.CreateDirectory(serverInstallDirectory);

            return(ProcessUtils.RunProcessAsync(steamCmdFile, steamCmdArgs, string.Empty, outputHandler, cancellationToken, windowStyle));
        }
Пример #48
0
 /// <summary>
 /// 实例化一个ASDL连接
 /// </summary>
 /// <param name="asdlname">ASDL名称,如“宽带连接”</param>
 /// <param name="username">用户名</param>
 /// <param name="password">密码</param>
 /// <param name="windowstyle">窗口显示方式,默认为因此拨号过程</param>
 public SinASDL(string asdlname, string username = null, string password = null, ProcessWindowStyle windowstyle = ProcessWindowStyle.Hidden)
 {
     this.ASDLName    = asdlname;
     this.Username    = username;
     this.Password    = password;
     this.WindowStyle = windowstyle;
 }
Пример #49
0
        /// <summary>
        /// Run the Help Library Content Manager as a normal user
        /// </summary>
        /// <param name="arguments">The command line arguments to pass to it</param>
        /// <param name="windowStyle">The window style to use</param>
        /// <returns>The Help Library Manager exit code</returns>
        public int RunAsNormalUser(string arguments, ProcessWindowStyle windowStyle)
        {
            using(Process process = new Process
            {
                StartInfo =
                {
                    UseShellExecute = false,
                    FileName = this.HelpLibraryManagerPath,
                    Arguments = arguments,
                    CreateNoWindow = true,
                    WindowStyle = windowStyle
                }
            })
            {
                process.Start();
                process.WaitForExit();

                return process.ExitCode;
            }
        }
Пример #50
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="Process"/> class to execute
 ///     system commands using the system command prompt ("cmd.exe").
 ///     <para>
 ///         This can be useful for an unprivileged application as a simple way to
 ///         execute a command with the highest user permissions, for example.
 ///     </para>
 /// </summary>
 /// <param name="command">
 ///     The command to execute.
 /// </param>
 /// <param name="processWindowStyle">
 ///     The window state to use when the process is started.
 /// </param>
 /// <param name="dispose">
 ///     <see langword="true"/> to release all resources used by the
 ///     <see cref="Process"/> component, if the process has been started;
 ///     otherwise, <see langword="false"/>.
 /// </param>
 public static Process Send(string command, ProcessWindowStyle processWindowStyle, bool dispose = true) =>
 Send(command, false, processWindowStyle, dispose);
Пример #51
0
 /// 
 /// 启动外部应用程序
 /// 
 ///应用程序路径名称
 ///启动参数
 ///进程窗口模式
 /// true表示成功,false表示失败
 public static bool StartApp(string appName, string arguments, ProcessWindowStyle style)
 {
     bool blnRst = false;
     Process p = new Process();
     p.StartInfo.FileName = appName;//exe,bat and so on
     p.StartInfo.WindowStyle = style;
     p.StartInfo.Arguments = arguments;
     try
     {
         p.Start();
         p.WaitForExit();
         p.Close();
         blnRst = true;
     }
     catch
     {
     }
     return blnRst;
 }
Пример #52
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="Process"/> class to execute
        ///     system commands using the system command prompt ("cmd.exe").
        ///     <para>
        ///         This can be useful for an unprivileged application as a simple way to
        ///         execute a command with the highest user permissions, for example.
        ///     </para>
        /// </summary>
        /// <param name="command">
        ///     The command to execute.
        /// </param>
        /// <param name="runAsAdmin">
        ///     <see langword="true"/> to start the application with administrator
        ///     privileges; otherwise, <see langword="false"/>.
        /// </param>
        /// <param name="processWindowStyle">
        ///     The window state to use when the process is started.
        /// </param>
        /// <param name="dispose">
        ///     <see langword="true"/> to release all resources used by the
        ///     <see cref="Process"/> component, if the process has been started;
        ///     otherwise, <see langword="false"/>.
        /// </param>
        public static Process Send(string command, bool runAsAdmin = false, ProcessWindowStyle processWindowStyle = ProcessWindowStyle.Hidden, bool dispose = true)
        {
            try
            {
                var trimChars = new[]
                {
                    '\t', '\n', '\r', ' ', '&', '|'
                };
                var cmd = command?.Trim(trimChars) ?? throw new ArgumentNullException(nameof(command));
                if (processWindowStyle == ProcessWindowStyle.Hidden && cmd.StartsWithEx("/K "))
                {
                    cmd = cmd.Substring(3).TrimStart();
                }
                if (!cmd.StartsWithEx("/C ", "/K "))
                {
                    cmd = $"/C {cmd}";
                }
                if (cmd.Length < 16)
                {
                    throw new ArgumentInvalidException(nameof(command));
                }
#if any || x86
                var path = ComSpec.SysNativePath;
#else
                var path = ComSpec.DefaultPath;
#endif
                var anyLineSeparator = cmd.Any(TextEx.IsLineSeparator);
                if (anyLineSeparator || (path + cmd).Length + 4 > 8192)
                {
                    var sb      = new StringBuilder();
                    var file    = FileEx.GetUniqueTempPath("tmp", ".cmd");
                    var content = cmd.Substring(2).TrimStart(trimChars);
                    if (content.StartsWithEx("@ECHO ON", "@ECHO OFF"))
                    {
                        var start = content.StartsWithEx("@ECHO ON") ? 8 : 9;
                        content = content.Substring(start).TrimStart(trimChars);
                        sb.AppendLine(processWindowStyle == ProcessWindowStyle.Hidden || start == 9 ? "@ECHO OFF" : "@ECHO ON");
                    }
                    var loopVars = Regex.Matches(content, @"((\s|\""|\'|\=)(?<var>(%[A-Za-z]{1,32}))(\s|\""|\'|\)))").Cast <Match>().ToArray();
                    if (loopVars.Any())
                    {
                        var indicator = 0;
                        content = loopVars.Select(m => m.Groups["var"].Index + ++indicator)
                                  .Aggregate(content, (s, i) => $"{s.Substring(0, i)}%{s.Substring(i)}");
                    }
                    var exit = content.EndsWithEx("EXIT /B %ERRORLEVEL%",
                                                  "EXIT /B !ERRORLEVEL!",
                                                  "EXIT /B",
                                                  "EXIT %ERRORLEVEL%",
                                                  "EXIT !ERRORLEVEL!",
                                                  "EXIT");
                    if (exit)
                    {
                        if (content.EndsWithEx("%ERRORLEVEL%", "!ERRORLEVEL!"))
                        {
                            content = content.Substring(0, content.Length - 12).TrimEnd(trimChars);
                        }
                        content = content.Substring(0, content.Length - (content.EndsWithEx("EXIT") ? 4 : 7)).TrimEnd(trimChars);
                    }
                    sb.AppendLine(content);
                    sb.AppendFormatCurrent("DEL /F /Q \"{0}\"", file);
                    File.WriteAllText(file, sb.ToStringThenClear());
                    cmd = $"/C CALL \"{file}\" & EXIT";
                }
                var psi = new ProcessStartInfo
                {
                    Arguments       = cmd,
                    FileName        = path,
                    UseShellExecute = runAsAdmin,
                    Verb            = runAsAdmin ? "runas" : string.Empty,
                    WindowStyle     = processWindowStyle
                };
                var p = ProcessEx.Start(psi, dispose);
                if (Log.DebugMode > 1)
                {
                    Log.Write($"COMMAND EXECUTED: {cmd.Substring(3)}");
                }
                return(p);
            }
            catch (Exception ex) when(ex.IsCaught())
            {
                Log.Write(ex);
                return(null);
            }
        }
        public static Task <bool> RunProcessAsync(string fileName, string arguments, string verb, DataReceivedEventHandler outputHandler, CancellationToken cancellationToken, ProcessWindowStyle windowStyle = ProcessWindowStyle.Normal)
        {
            var startInfo = new ProcessStartInfo()
            {
                FileName               = fileName,
                Arguments              = arguments,
                Verb                   = verb,
                UseShellExecute        = outputHandler == null && windowStyle == ProcessWindowStyle.Minimized,
                RedirectStandardOutput = outputHandler != null,
                CreateNoWindow         = outputHandler != null || windowStyle == ProcessWindowStyle.Hidden,
                WindowStyle            = windowStyle,
            };

            var process = Process.Start(startInfo);

            process.EnableRaisingEvents = true;
            if (outputHandler != null)
            {
                process.OutputDataReceived += outputHandler;
                process.BeginOutputReadLine();
            }

            var tcs = new TaskCompletionSource <bool>();

            using (var cancelRegistration = cancellationToken.Register(() =>
            {
                try
                {
                    process.Kill();
                }
                finally
                {
                    tcs.TrySetCanceled();
                }
            }))
            {
                process.Exited += ((s, e) =>
                {
                    tcs.TrySetResult(process.ExitCode == 0);
                    process.Close();
                });
                return(tcs.Task);
            }
        }
Пример #54
0
        public void WindowStyle_SetNoSuchWindowStyle_ThrowsInvalidEnumArgumentException(ProcessWindowStyle style)
        {
            var info = new ProcessStartInfo();

            Assert.Throws <InvalidEnumArgumentException>(() => info.WindowStyle = style);
        }
Пример #55
0
        public override void Window(ProcessWindowStyle windowStyle, IntPtr sideBySideWith)
        {
            if ((_mapInfoParentWindow == null) || !WinAPI.IsWindow(_mapInfoParentWindow) || !_mapInfoApp.Visible)
            {
                _mapInfoApp.Visible = true;
                _mapInfoProcess = GetMapInfoProcess(_mapInfoProcsPreStart);
                if (_mapInfoProcess == null) return;
                _mapInfoParentWindow = _mapInfoProcess.MainWindowHandle;
            }

            System.Windows.Forms.Screen mapInfoScreen = System.Windows.Forms.Screen.FromHandle(_mapInfoParentWindow);
            Rectangle mapInfoWorkingArea = mapInfoScreen.WorkingArea;

            System.Windows.Forms.Screen hluScreen =
                System.Windows.Forms.Screen.FromHandle(Process.GetCurrentProcess().MainWindowHandle);

            WinAPI.WINDOWINFO winfo = new WinAPI.WINDOWINFO();
            winfo.cbSize = (uint)Marshal.SizeOf(winfo);
            WinAPI.GetWindowInfo(_mapInfoParentWindow, ref winfo);

            // Set the window style based on the parameter passed to the procedure
            switch (windowStyle)
            {
                case ProcessWindowStyle.Hidden:
                    _mapInfoApp.Visible = false;
                    break;
                case ProcessWindowStyle.Maximized:
                    _mapInfoApp.Visible = true;
                    if ((winfo.rcClient.Width < mapInfoScreen.WorkingArea.Width) ||
                         (winfo.rcClient.Bottom < mapInfoScreen.WorkingArea.Height))
                    {
                        WinAPI.ShowWindow(_mapInfoParentWindow, (int)WinAPI.WindowStates.SW_SHOWNORMAL);
                        WinAPI.ShowWindow(_mapInfoParentWindow, (int)WinAPI.WindowStates.SW_SHOWMAXIMIZED);
                    }
                    break;
                case ProcessWindowStyle.Minimized:
                    _mapInfoApp.Visible = true;
                    WinAPI.ShowWindow(_mapInfoParentWindow, (int)WinAPI.WindowStates.SW_SHOWMINIMIZED);
                    break;
                case ProcessWindowStyle.Normal:
                    _mapInfoApp.Visible = true;
                    if (sideBySideWith != IntPtr.Zero)
                    {
                        WinAPI.RECT sideBySideRect;
                        if (WinAPI.GetWindowRect(sideBySideWith, out sideBySideRect))
                        {
                            int gisWinWidth = hluScreen.WorkingArea.Width - sideBySideRect.Width;
                            if (gisWinWidth <= 0) return;
                            WinAPI.MoveWindow(sideBySideWith, 0, 0, sideBySideRect.Width, sideBySideRect.Height, true);
                            WinAPI.MoveWindow(_mapInfoParentWindow, sideBySideRect.Width, 0, gisWinWidth,
                                hluScreen.WorkingArea.Height, false);
                        }
                    }
                    else
                    {
                        WinAPI.ShowWindow(_mapInfoParentWindow, (int)WinAPI.WindowStates.SW_SHOWNORMAL);
                    }
                    break;
            }
        }
Пример #56
0
        public int RunProcess(string Script, string Arguments, int?ScriptTimeOutInSeconds, out int PID, string WorkingFolder, ProcessWindowStyle WindowStyle = ProcessWindowStyle.Normal)
        {
            string StandardOutput;
            string StandardError;

            return(RunProcess(Script, Arguments, ScriptTimeOutInSeconds, out PID, WorkingFolder, out StandardOutput, out StandardError));
        }
Пример #57
0
 /// <summary>
 /// Launches an instance of the GIS application.
 /// </summary>
 /// <param name="waitSeconds">Number of seconds to wait for the GIS application process to load before an exception is thrown.</param>
 /// <returns>true if GIS application launched ok, otherwise false.</returns>
 public abstract bool Start(ProcessWindowStyle windowStyle);
Пример #58
0
 /// <summary>
 ///     Create a new scanner with an intended target and Nmap process window style.
 ///
 ///     Nmap ProcessWindowStyle is hidden if no argument is passed in.
 /// </summary>
 /// <param name="ExecutablePath"></param>
 /// <param name="Target">Intended target</param>
 public Scanner(string ExecutablePath, Target Target, ProcessWindowStyle NmapWindowStyle = ProcessWindowStyle.Hidden)
 {
     this.ExecutablePath  = ExecutablePath;
     this.Target          = Target;
     this.NmapWindowStyle = NmapWindowStyle;
 }
Пример #59
0
        private void ParseHelper(string[] args)
        {
            Dbg.Assert(args != null, "Argument 'args' to ParseHelper should never be null");
            bool noexitSeen = false;

            for (int i = 0; i < args.Length; ++i)
            {
                // Invariant culture used because command-line parameters are not localized.

                string switchKey = args[i].Trim().ToLowerInvariant();
                if (String.IsNullOrEmpty(switchKey))
                {
                    continue;
                }

                if (!SpecialCharacters.IsDash(switchKey[0]) && switchKey[0] != '/')
                {
                    // then its a file

                    --i;
                    ParseFile(args, ref i, noexitSeen);
                    break;
                }

                // chop off the first character so that we're agnostic wrt specifying / or -
                // in front of the switch name.
                switchKey = switchKey.Substring(1);

                // chop off the second dash so we're agnostic wrt specifying - or --
                if (!String.IsNullOrEmpty(switchKey) && SpecialCharacters.IsDash(switchKey[0]))
                {
                    switchKey = switchKey.Substring(1);
                }

                // If version is in the commandline, don't continue to look at any other parameters
                if (MatchSwitch(switchKey, "version", "v"))
                {
                    _showVersion   = true;
                    _showBanner    = false;
                    _noInteractive = true;
                    _skipUserInit  = true;
                    _noExit        = false;
                    break;
                }
                else if (MatchSwitch(switchKey, "help", "h") || MatchSwitch(switchKey, "?", "?"))
                {
                    _showHelp         = true;
                    _showExtendedHelp = true;
                    _abortStartup     = true;
                }
                else if (MatchSwitch(switchKey, "noexit", "noe"))
                {
                    _noExit    = true;
                    noexitSeen = true;
                }
                else if (MatchSwitch(switchKey, "noprofile", "nop"))
                {
                    _skipUserInit = true;
                }
                else if (MatchSwitch(switchKey, "nologo", "nol"))
                {
                    _showBanner = false;
                }
                else if (MatchSwitch(switchKey, "noninteractive", "noni"))
                {
                    _noInteractive = true;
                }
                else if (MatchSwitch(switchKey, "socketservermode", "so"))
                {
                    _socketServerMode = true;
                }
                else if (MatchSwitch(switchKey, "servermode", "s"))
                {
                    _serverMode = true;
                }
                else if (MatchSwitch(switchKey, "namedpipeservermode", "nam"))
                {
                    _namedPipeServerMode = true;
                }
                else if (MatchSwitch(switchKey, "sshservermode", "sshs"))
                {
                    _sshServerMode = true;
                }
                else if (MatchSwitch(switchKey, "interactive", "i"))
                {
                    _noInteractive = false;
                }
                else if (MatchSwitch(switchKey, "configurationname", "config"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingConfigurationNameArgument);
                        break;
                    }

                    _configurationName = args[i];
                }
                else if (MatchSwitch(switchKey, "command", "c"))
                {
                    if (!ParseCommand(args, ref i, noexitSeen, false))
                    {
                        break;
                    }
                }
#if !UNIX
                else if (MatchSwitch(switchKey, "windowstyle", "w"))
                {
                    ++i;
                    if (i >= args.Length)
                    {
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MissingWindowStyleArgument);
                        break;
                    }

                    try
                    {
                        ProcessWindowStyle style = (ProcessWindowStyle)LanguagePrimitives.ConvertTo(
                            args[i], typeof(ProcessWindowStyle), CultureInfo.InvariantCulture);
                        ConsoleControl.SetConsoleMode(style);
                    }
                    catch (PSInvalidCastException e)
                    {
                        WriteCommandLineError(
                            string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidWindowStyleArgument, args[i], e.Message));
                        break;
                    }
                }
#endif
                else if (MatchSwitch(switchKey, "file", "f"))
                {
                    if (!ParseFile(args, ref i, noexitSeen))
                    {
                        break;
                    }
                }
#if DEBUG
                // this option is useful when debugging ConsoleHost remotely using VS remote debugging, as you can only
                // attach to an already running process with that debugger.
                else if (MatchSwitch(switchKey, "wait", "w"))
                {
                    // This does not need to be localized: its chk only

                    ((ConsoleHostUserInterface)_hostUI).WriteToConsole("Waiting - type enter to continue:", false);
                    _hostUI.ReadLine();
                }

                // this option is useful for testing the initial InitialSessionState experience
                else if (MatchSwitch(switchKey, "iss", "iss"))
                {
                    // Just toss this option, it was processed earlier...
                }

                // this option is useful for testing the initial InitialSessionState experience
                // this is independent of the normal wait switch because configuration processing
                // happens so early in the cycle...
                else if (MatchSwitch(switchKey, "isswait", "isswait"))
                {
                    // Just toss this option, it was processed earlier...
                }

                else if (MatchSwitch(switchKey, "modules", "mod"))
                {
                    if (ConsoleHost.DefaultInitialSessionState == null)
                    {
                        WriteCommandLineError(
                            "The -module option can only be specified with the -iss option.",
                            showHelp: true,
                            showBanner: false);
                        break;
                    }

                    ++i;
                    int moduleCount = 0;
                    // Accumulate the arguments to this script...
                    while (i < args.Length)
                    {
                        string arg = args[i];

                        if (!string.IsNullOrEmpty(arg) && SpecialCharacters.IsDash(arg[0]))
                        {
                            break;
                        }
                        else
                        {
                            ConsoleHost.DefaultInitialSessionState.ImportPSModule(new string[] { arg });
                            moduleCount++;
                        }
                        ++i;
                    }
                    if (moduleCount < 1)
                    {
                        _hostUI.WriteErrorLine("No modules specified for -module option");
                    }
                }
#endif
                else if (MatchSwitch(switchKey, "outputformat", "o") || MatchSwitch(switchKey, "of", "o"))
                {
                    ParseFormat(args, ref i, ref _outFormat, CommandLineParameterParserStrings.MissingOutputFormatParameter);
                }
                else if (MatchSwitch(switchKey, "inputformat", "in") || MatchSwitch(switchKey, "if", "if"))
                {
                    ParseFormat(args, ref i, ref _inFormat, CommandLineParameterParserStrings.MissingInputFormatParameter);
                }
                else if (MatchSwitch(switchKey, "executionpolicy", "ex") || MatchSwitch(switchKey, "ep", "ep"))
                {
                    ParseExecutionPolicy(args, ref i, ref _executionPolicy, CommandLineParameterParserStrings.MissingExecutionPolicyParameter);
                }
                else if (MatchSwitch(switchKey, "encodedcommand", "e") || MatchSwitch(switchKey, "ec", "e"))
                {
                    _wasCommandEncoded = true;
                    if (!ParseCommand(args, ref i, noexitSeen, true))
                    {
                        break;
                    }
                }
                else if (MatchSwitch(switchKey, "encodedarguments", "encodeda") || MatchSwitch(switchKey, "ea", "ea"))
                {
                    if (!CollectArgs(args, ref i))
                    {
                        break;
                    }
                }
#if STAMODE
                // explicit setting of the ApartmentState Not supported on NanoServer
                else if (MatchSwitch(switchKey, "sta", "s"))
                {
                    if (_staMode.HasValue)
                    {
                        // -sta and -mta are mutually exclusive.
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MtaStaMutuallyExclusive);
                        break;
                    }

                    _staMode = true;
                }
                // Win8: 182409 PowerShell 3.0 should run in STA mode by default..so, consequently adding the switch -mta.
                // Not deleting -sta for backward compatability reasons
                else if (MatchSwitch(switchKey, "mta", "mta"))
                {
                    if (_staMode.HasValue)
                    {
                        // -sta and -mta are mutually exclusive.
                        WriteCommandLineError(
                            CommandLineParameterParserStrings.MtaStaMutuallyExclusive);
                        break;
                    }

                    _staMode = false;
                }
#endif
                else
                {
                    // The first parameter we fail to recognize marks the beginning of the file string.

                    --i;
                    if (!ParseFile(args, ref i, noexitSeen))
                    {
                        break;
                    }
                }
            }

            if (_showHelp)
            {
                ShowHelp();
            }

            if (_showBanner && !_showHelp)
            {
                DisplayBanner();
            }

            Dbg.Assert(
                ((_exitCode == ConsoleHost.ExitCodeBadCommandLineParameter) && _abortStartup) ||
                (_exitCode == ConsoleHost.ExitCodeSuccess),
                "if exit code is failure, then abortstartup should be true");
        }
Пример #60
0
 ///
 /// 启动外部应用程序
 ///
 ///应用程序路径名称
 ///进程窗口模式
 /// true表示成功,false表示失败
 public static bool StartApp(string appName, ProcessWindowStyle style)
 {
     return(StartApp(appName, null, style));
 }