public static void kill(Process P,bool force) { if (!isKilling(P) && P.Id != Process.GetCurrentProcess().Id) { if (force) { new frmKill(P).Show(); } else { try { P.CloseMainWindow(); } catch { //NOOP } } } }
public void ExitCurrentGame() { try { if (currentProcess != null) { currentProcess.CloseMainWindow(); currentProcess.WaitForExit(); currentProcess = null; } } catch { } }
private static void StartIisExpress() { var startInfo = new ProcessStartInfo { WindowStyle = ProcessWindowStyle.Normal, ErrorDialog = true, LoadUserProfile = true, CreateNoWindow = false, UseShellExecute = false, Arguments = string.Format("/path:\"{0}\" /port:{1}", @"C:\Users\ian\Documents\Visual Studio 2015\Projects\SimpleCalculator\SimpleCalculator", "8888") }; var programfiles = string.IsNullOrEmpty(startInfo.EnvironmentVariables["programfiles"]) ? startInfo.EnvironmentVariables["programfiles(x86)"] : startInfo.EnvironmentVariables["programfiles"]; startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe"; try { _iisProcess = new Process { StartInfo = startInfo }; _iisProcess.Start(); _iisProcess.WaitForExit(); } catch { _iisProcess.CloseMainWindow(); _iisProcess.Dispose(); } }
/// <summary> /// Invoke the Commandline arguments from the command given with elevated previlages. /// </summary> /// <param name="command">CMD command</param> /// <param name="waitTillExit">If you want to wait for the command to execute</param> /// <param name="closeOutputWindow">Closes main window after execution for UI based application</param> public static void Invoke(string command, bool waitTillExit = false, bool closeOutputWindow = false) { try { System.Diagnostics.ProcessStartInfo ProcessInfo; System.Diagnostics.Process Process = new System.Diagnostics.Process(); ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + command); ProcessInfo.CreateNoWindow = false; ProcessInfo.Verb = "runas"; ProcessInfo.UseShellExecute = true; Process.EnableRaisingEvents = true; Process = System.Diagnostics.Process.Start(ProcessInfo); if (waitTillExit == true) { Process.WaitForExit(); } if (closeOutputWindow == true) { Process.CloseMainWindow(); } Process.Close(); } catch { } }
private void StartIisExpress() { var applicationHostConfig = CreateApplicationHostConfig(); var applicationHostPath = Path.GetFullPath("applicationHost.config"); File.WriteAllText(applicationHostPath, applicationHostConfig); var startInfo = new ProcessStartInfo { UseShellExecute = false, WindowStyle = ProcessWindowStyle.Minimized, CreateNoWindow = !_options.ShowIisExpressWindow, Arguments = string.Format("/config:\"{0}\" /systray:true", applicationHostPath) }; var programfiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe"; try { _process = new Process { StartInfo = startInfo }; _process.Start(); _manualResetEvent.Set(); _process.WaitForExit(); } catch (Exception ex) { Console.WriteLine("Error starting IIS Express: " + ex); _process.CloseMainWindow(); _process.Dispose(); } }
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { p.CloseMainWindow(); p.Close(); p = null; }
private void btnMissedCalls_Click(object sender, EventArgs e) { //IsAccepted = false; //PopulateData(); try { using (TaxiDataContext dbX = new TaxiDataContext()) { var obj = dbX.CallerIdVOIP_Configurations.FirstOrDefault(); if (obj != null) { System.Diagnostics.Process proc = System.Diagnostics.Process.GetProcesses().FirstOrDefault(c => c.ProcessName.Contains("CabTreasureEmeraldCallRecording")); if (proc != null) { proc.Kill(); proc.CloseMainWindow(); proc.Close(); } string arg = obj.UserName.ToStr() + " " + obj.Password.ToStr(); System.Diagnostics.Process.Start(Application.StartupPath + "\\CabTreasureEmeraldCallRecording.exe", arg); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken) { if (processStartInfo == null) { throw new ArgumentNullException("processStartInfo"); } // force some settings in the start info so we can capture the output processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; processStartInfo.CreateNoWindow = true; var tcs = new TaskCompletionSource<ProcessResults>(); var standardOutput = new List<string>(); var standardError = new List<string>(); var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true, }; process.OutputDataReceived += (sender, args) => { if (args.Data != null) { standardOutput.Add(args.Data); } }; process.ErrorDataReceived += (sender, args) => { if (args.Data != null) { standardError.Add(args.Data); } }; process.Exited += (sender, args) => tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError)); cancellationToken.Register(() => { tcs.TrySetCanceled(); process.CloseMainWindow(); }); cancellationToken.ThrowIfCancellationRequested(); if (process.Start() == false) { tcs.TrySetException(new InvalidOperationException("Failed to start process")); } process.BeginOutputReadLine(); process.BeginErrorReadLine(); return tcs.Task; }
private static void StartIisExpress() { var projectPath = $"{Environment.CurrentDirectory}\\..\\..\\..\\..\\ContosoUniversity.Web.Mvc\\obj\\Publish"; projectPath = System.IO.Path.GetFullPath(projectPath); var startInfo = new ProcessStartInfo { WindowStyle = ProcessWindowStyle.Normal, ErrorDialog = true, LoadUserProfile = true, CreateNoWindow = false, UseShellExecute = false, Arguments = string.Format("/path:\"{0}\" /port:{1}", projectPath, Port) }; var programfiles = string.IsNullOrEmpty(startInfo.EnvironmentVariables["programfiles"]) ? startInfo.EnvironmentVariables["programfiles(x86)"] : startInfo.EnvironmentVariables["programfiles"]; startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe"; try { _iisProcess = new Process { StartInfo = startInfo }; _iisProcess.Start(); _iisProcess.WaitForExit(); } catch { _iisProcess.CloseMainWindow(); _iisProcess.Dispose(); } }
private static void StartIisExpress() { var startInfo = new ProcessStartInfo { WindowStyle = ProcessWindowStyle.Normal, ErrorDialog = true, LoadUserProfile = true, CreateNoWindow = false, UseShellExecute = false, Arguments = string.Format("/config:{0} /site:{1}", @"../../../.vs/config/applicationhost.config", "Web") }; var programfiles = string.IsNullOrEmpty(startInfo.EnvironmentVariables["programfiles"]) ? startInfo.EnvironmentVariables["programfiles(x86)"] : startInfo.EnvironmentVariables["programfiles"]; startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe"; try { _iisProcess = new Process { StartInfo = startInfo }; _iisProcess.Start(); _iisProcess.WaitForExit(); } catch { _iisProcess.CloseMainWindow(); _iisProcess.Dispose(); } }
public void Close() { try { if (AgentType == eAgentType.Service) { if (mGingerNodeInfo != null) { // this is plugin driver GingerNodeProxy GNP = new GingerNodeProxy(mGingerNodeInfo); GNP.GingerGrid = WorkSpace.Instance.LocalGingerGrid; GNP.CloseDriver(); if (mProcess != null) { // mProcess.Kill(); //mProcess.Close(); //GingerCore.General.DoEvents(); mProcess.CloseMainWindow(); } mGingerNodeInfo = null; // GNP.Shutdown(); return; } } if (Driver == null) { return; } Driver.IsDriverRunning = false; if (Driver.Dispatcher != null) { Driver.Dispatcher.Invoke(() => { Driver.CloseDriver(); Thread.Sleep(1000); }); } else { Driver.CloseDriver(); } if (MSTATask != null) { // Using Cancelleation token soucrce to cancel CancelTask = new BackgroundWorker(); CancelTask.DoWork += new DoWorkEventHandler(CancelTMSTATask); CancelTask.RunWorkerAsync(); } Driver = null; } finally { OnPropertyChanged(Fields.Status); OnPropertyChanged(Fields.IsWindowExplorerSupportReady); } }
private static void kill(Process process) { process.CloseMainWindow(); if (!process.HasExited) { process.Kill(); } process.WaitForExit(); process.Close(); }
protected override void Dispose(bool disposing) { if (SerialProcess != null && !SerialProcess.HasExited) { SerialProcess.CloseMainWindow(); } base.Dispose(disposing); }
public async Task Close() { if (_process == null) return; _process.Exited -= ProcessExited; await Task.Run(() => { //TODO: Use Process.WaitForExit to wait for the process to exit _isRunning = _process.CloseMainWindow(); }); }
void CloseApplication(Process process, bool force) { int num = force ? 1 : 0x2710; DateTime now = DateTime.Now; TimeSpan zero = TimeSpan.Zero; bool flag = false; IntPtr ptr = IntPtr.Zero; while (zero.TotalMilliseconds < num){ Trace.WriteLine(DateTime.Now + "\tCall Process.Refresh() at WinApplicationAdapter.CloseApplication"); process.Refresh(); Trace.WriteLine(DateTime.Now + "\tCall Process.Refresh() success"); Trace.WriteLine(DateTime.Now +"\tCall Process.MainWindowHandle at WinApplicationAdapter.CloseApplication"); IntPtr mainWindowHandle = IntPtr.Zero; try{ mainWindowHandle = process.MainWindowHandle; } catch (InvalidOperationException){ } if ((mainWindowHandle != ptr) && (mainWindowHandle != IntPtr.Zero)){ ptr = mainWindowHandle; try{ process.CloseMainWindow(); } catch (Exception exception){ Logger.Instance.AddMessage(string.Format("Process{0}.CloseMainWindow return error:\n'{1}'",process.ProcessName, exception.Message)); } } Trace.WriteLine(DateTime.Now + "\tCall Process.MainWindowHandle success"); try{ if (process.WaitForExit(Math.Min(0x3e8, num - ((int) zero.TotalMilliseconds)))){ flag = true; break; } } catch (Exception exception2){ Logger.Instance.AddMessage(string.Format("Process.WaitForExit return error:\n'{0}'",exception2.Message)); } zero = DateTime.Now - now; } if (!flag){ if (!force){ Logger.Instance.AddMessage(string.Format("The process '{0}' was not closed in '{1}' millisecond after the Process.CloseMainWindow was invoked, trying to kill this process",process.ProcessName, num)); } try{ process.Kill(); } catch (Exception exception3){ Logger.Instance.AddMessage(string.Format("Process name: '{0}' is not killed.\nReason:\n'{1}'",process.ProcessName, exception3.Message)); } if (!process.WaitForExit(0x2710)){ throw new WarningException( string.Format("Process name: '{0}' doesn't exited in 10 seconds after the Process.Kill was invoked",process.ProcessName)); } } }
public static void SendCloseMessage(Process process) { if(process.MainWindowHandle != IntPtr.Zero) { process.CloseMainWindow(); } foreach (ProcessThread pt in process.Threads) { EnumThreadWindows((uint)pt.Id, EnumThreadCallback, IntPtr.Zero); } }
public void Start() { try { Console.WriteLine("Launching IIS Express: {0} {1}", _startInfo.FileName, _startInfo.Arguments); IisProcess = Process.Start(_startInfo); } catch { IisProcess.CloseMainWindow(); IisProcess.Dispose(); } }
//------------------------------------------- // process をクローズする //------------------------------------------- public static void Close() { if (mFMEprocess != null) { if (!mFMEprocess.HasExited) { mFMEprocess.CloseMainWindow(); mFMEprocess.WaitForExit(); } mFMEprocess.Close(); mFMEprocess = null; } }
public async Task Close() { if (_process == null) { return; } _process.Exited -= ProcessExited; await Task.Run(() => { _isRunning = _process.CloseMainWindow(); }); }
public static void CloseCMD() { try { CloseSpringbootServer(); process.CloseMainWindow(); process.Close(); } catch (Exception e) { Console.WriteLine(e.StackTrace); } }
static void Main(string[] args) { var bdir = AppDomain.CurrentDomain.BaseDirectory; var param = "/c "+"java -jar " + bdir + "sat4j-pb.jar " + bdir + "generatedForVideoTutorial.opb > c:\\myou.txt"; var processStartInfo = new ProcessStartInfo(@"cmd.exe", param) { UseShellExecute = true, RedirectStandardOutput = false, RedirectStandardInput = false, CreateNoWindow = false, WindowStyle = ProcessWindowStyle.Minimized }; _cmdExe = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; _cmdExe.Start(); StartTime = DateTime.Now; while (true) { CurrentTime = DateTime.Now; var diff = CurrentTime.Subtract(StartTime).TotalSeconds; if (diff >= 10) { try { SendCtrlC(_cmdExe.MainWindowHandle); } catch (Exception exception) { _cmdExe.CloseMainWindow(); throw; } _cmdExe.CloseMainWindow(); break; } } }
private void 打印ToolStripMenuItem_Click(object sender, EventArgs e) { //为了简化处理, 这直接将文件送到打印机打印,不是别好 //有兴趣的话可以尝试打印richtextbox的内容, 要留图和格式 if (filename == null || filename == "") { MessageBox.Show("save first,please!"); return; } System.Diagnostics.Process p = new System.Diagnostics.Process(); try { p.StartInfo.FileName = filename; p.StartInfo.WorkingDirectory = (new FileInfo(filename)).DirectoryName; p.StartInfo.CreateNoWindow = true; p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.Verb = "Print"; p.Start(); if (!p.HasExited) { p.WaitForInputIdle(10000); int i = 1; bool running = true; while (running && i <= 20) { System.Threading.Thread.Sleep(500); if (p.HasExited) { running = false; } else { running = !p.CloseMainWindow(); } i++; } if (running && !p.HasExited) { p.Kill(); } } p.Dispose(); } catch (Exception ee) { MessageBox.Show(ee.Message); } }
public static async Task CloseBotProcessAsync(System.Diagnostics.Process proc, CharacterProfile profile) { var procName = proc.ProcessName; profile.Log("Attempting to close {0}", procName); proc.CloseMainWindow(); if (await WaitForProcessToExitAsync(proc, TimeSpan.FromSeconds(10))) { profile.Log("Successfully closed {0} gracefully", procName); return; } profile.Log("Killing {0}", procName); proc.Kill(); }
static void Main(string[] args) { Process processClient = new Process(); processClient.StartInfo.FileName = "ProcessClient.exe"; processClient.StartInfo.UseShellExecute = true; // musts be true processClient.Start(); Thread.Sleep(2000); processClient.CloseMainWindow(); processClient.WaitForExit(); processClient.Close(); LogIt("Client quit. Server terminating."); Console.ReadKey(); }
public virtual void KillProcess(Process p, bool gracefully = false) { Contract.Requires<ArgumentNullException>(p != null); if (gracefully) { p.CloseMainWindow(); var i = 0; while (!p.SafeHasExited()) { i++; if (i > 4) break; Thread.Sleep(1000); } } if (!p.SafeHasExited()) p.Kill(); }
protected override void ExecuteTask() { outputPathForExec = exec.Output; FileManager.CreateFileIfNotExists(exec.Output); using (Process process = new Process()) { if (String.IsNullOrEmpty(exec.WorkingDirect)) { process.StartInfo.WorkingDirectory = PackageManagerWorkspace.PackagePath; } else { FileManager.CreateDirectoryIfNotExists(exec.WorkingDirect); process.StartInfo.WorkingDirectory = exec.WorkingDirect; } process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.FileName = string.IsNullOrEmpty(exec.BaseDirectory) ? exec.Program : Path.Combine(PackageManagerWorkspace.PackagePath, exec.BaseDirectory, exec.Program); ; process.StartInfo.Arguments = exec.CommandLine; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler); process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler); process.Start(); if (exec.Timeout > 0) { process.WaitForExit(exec.Timeout); if (process.HasExited == false) { if (process.Responding) process.CloseMainWindow(); else process.Kill(); throw new TimeoutException("TimeOut program execution: " + exec.Program); } } else { process.WaitForExit(); } } }
public frmKill(Process Proc) { //prevents deleting of the referenced object P = Process.GetProcessById(Proc.Id); InitializeComponent(); try { P.CloseMainWindow(); } catch { //There is no Window to close wo we kill it instantly. i = MAXWAIT; } tKill.Start(); label1.Text = "Killing PID: " + P.Id.ToString(); }
static void Main(string[] args) { PrintTypes("PipeTestClient.exe"); CancellationTokenSource source = new CancellationTokenSource(); Console.WriteLine("Server stared... Starting Pipe"); StartServer(source); Console.WriteLine("Starting Tool to be analysed"); Process process = new Process(); process.StartInfo.FileName = "PipeTestClient.exe"; process.Start(); Console.WriteLine("Enter to stop"); Console.ReadLine(); source.Cancel(); process.CloseMainWindow(); Console.ReadLine(); }
/** On Unix Process.Kill will not kill the forked jvm process. Due to the use of `eval' in standalone.sh it will only kill the shell script. This method kills the first level subprocesses as well. */ public static void killServer(Process process) { if (isUnix()) { /* Kill the process and subprocesses. */ Process killProcess = new Process(); killProcess.StartInfo.FileName = "bash"; killProcess.StartInfo.Arguments = String.Format("-c \"ps h --format pid --pid {0} --ppid {0} | xargs kill\"", process.Id); killProcess.Start(); killProcess.WaitForExit(); } else { process.CloseMainWindow(); } if (!process.HasExited) { process.Kill(); } process.WaitForExit(); process.Close(); }
static public Task<Process> RunProcessAsync( string fileName, string arguments = null, CancellationToken cancellationToken = default(CancellationToken), IProgress<ProcessProgressEventArgs> progress = null, object objectState = null) { TaskCompletionSource<Process> taskCS = new TaskCompletionSource<Process>(); Process process = new Process() { StartInfo = new ProcessStartInfo(fileName) { UseShellExecute = false, Arguments = arguments, RedirectStandardOutput = progress != null }, EnableRaisingEvents = true }; process.Exited += (sender, localEventArgs) => { taskCS.SetResult(process); }; cancellationToken .ThrowIfCancellationRequested(); process.Start(); cancellationToken.Register(() => { process.CloseMainWindow(); }); return taskCS.Task; }
public void ejecutarProgramaCMD(String prog, String commando) { int timeOut = 10000; System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe"); psi.UseShellExecute = false; psi.Arguments = commando; psi.CreateNoWindow = true; psi.ErrorDialog = true; psi.RedirectStandardError = true; psi.RedirectStandardOutput = true; psi.RedirectStandardInput = true; System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); Encoding encoding = proc.StandardOutput.CurrentEncoding; System.IO.StreamWriter SW = proc.StandardInput; SW.WriteLine(@prog + " " + @commando); SW.Close(); System.IO.StreamWriter SR = new System.IO.StreamWriter(Padre.PATH_LOCAL_INSTALADOR + @"\SqlCreate.log", false, encoding); SR.Write(proc.StandardOutput.ReadToEnd()); SR.Close(); proc.WaitForExit(timeOut); if (proc.HasExited == false) { if (proc.Responding) { //El proceso estaba respondiendo; cerrar la ventana principal. proc.CloseMainWindow(); } else { //El proceso no estaba respondiendo; forzar el cierre del proceso. proc.Kill(); } } }
static void Main(string[] args) { string BrowserExec = args[0]; int XRes = int.Parse(args[1]); int YRes = int.Parse(args[2]); string Url = args[3]; string Filename = args[4]; try { // Change resolution changeResolution(XRes, YRes); // Start browser Process p = new Process(); p.StartInfo.FileName = BrowserExec; p.StartInfo.Arguments = Url; p.Start(); // Wait for window to open, and then maximize and bring to front System.Threading.Thread.Sleep(500); maximizeFront(p.MainWindowHandle); // Wait for page to load System.Threading.Thread.Sleep(5000); // Take screenshot saveScreenshot(Filename); // Exit browser p.CloseMainWindow(); System.Threading.Thread.Sleep(500); // Is this necessary!? if (!p.HasExited) p.Kill(); } catch (Exception e) { ; // Do nothing, ugly but necessary } }
public bool CloseMainWindow(int PID, int timeout) { int timer = 0; int sleeptime = 500; System.Diagnostics.Process p = null; bool rval; try { p = System.Diagnostics.Process.GetProcessById(PID); rval = p.CloseMainWindow(); if (!rval) { return(rval); } else { while (timer < timeout && !p.HasExited) { System.Threading.Thread.Sleep(sleeptime); timer += sleeptime; } if (p.HasExited) { return(true); } else { return(false); } } } catch (Exception exc) { LogEvent(exc.Source, "CloseMainWindow(int, int)", exc.ToString(), 4); return(false); } }
public void Close() { try { if (Agent.AgentType == Agent.eAgentType.Service) { if (gingerNodeInfo != null) { // this is plugin driver on local machine GingerNodeProxy.GingerGrid = WorkSpace.Instance.LocalGingerGrid; GingerNodeProxy.CloseDriver(); gingerNodeInfo.Status = GingerNodeInfo.eStatus.Ready; if (mProcess != null) // it means a new plugin process was started for this agent - so we close it { // Remove the node from the grid WorkSpace.Instance.LocalGingerGrid.NodeList.Remove(gingerNodeInfo); // Close the plugin process mProcess.CloseMainWindow(); } GingerNodeProxy = null; gingerNodeInfo = null; return; } else { if (GingerNodeProxy != null) { // Running on Remote Grid GingerNodeProxy.CloseDriver(); GingerNodeProxy.Disconnect(); GingerNodeProxy = null; } } } if (Driver == null) { return; } Driver.IsDriverRunning = false; if (Driver is IDriverWindow && ((IDriverWindow)Driver).ShowWindow) { DriversWindowUtils.OnDriverWindowEvent(DriverWindowEventArgs.eEventType.CloseDriverWindow, Driver, this); Driver.CloseDriver(); } else if (Driver.Dispatcher != null) { Driver.Dispatcher.Invoke(() => { Driver.CloseDriver(); Thread.Sleep(1000); }); } else { Driver.CloseDriver(); } if (MSTATask != null) { // Using cancellation token source to cancel CancelTask = new BackgroundWorker(); CancelTask.DoWork += new DoWorkEventHandler(Agent.CancelTMSTATask); CancelTask.RunWorkerAsync(); } Driver = null; } finally { Agent.OnPropertyChanged(nameof(AgentOperations.Status)); Agent.OnPropertyChanged(nameof(AgentOperations.IsWindowExplorerSupportReady)); } }
public async void onPrintRequested(string selected) { try { this.events.PublishOnUIThread(new ViewStartPrintProgressCommand()); } catch { } // System.Threading.Thread.Sleep(2000); if (selected == "before") { // PrinterCanceller.CancelPrint(); string path = System.IO.Path.Combine( System.IO.Path.GetDirectoryName( this.GetType().Assembly.Location), "Printings", GlobalCounters.numberOfCurrentPrintings.ToString() + ".pdf"); var success = await _mainBrowser.PrintToPdfAsync(path, new PdfPrintSettings { MarginType = CefPdfPrintMarginType.Custom, MarginBottom = 10, MarginTop = 0, MarginLeft = 20, MarginRight = 10, }); System.Threading.Thread.Sleep(3000); if (success) { try { iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(path); int numberOfPages = pdfReader.NumberOfPages; if (GlobalCounters.numberOfCurrentPrintings + numberOfPages <= Convert.ToInt32(this.numberOfAvailablePagesToPrint)) { try { this.log.Info("Invoking Action: ViewPrintRequested " + numberOfPages.ToString() + " pages."); } catch { } try { TaskbarManager.HideTaskbar(); } catch { } try { System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(); info.UseShellExecute = true; info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; info.Verb = "print"; info.FileName = path; info.CreateNoWindow = true; System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo = info; p.Start(); // p.WaitForInputIdle(); p.WaitForExit(); p.CloseMainWindow(); if (false == p.CloseMainWindow()) { try { p.Kill(); } catch { } } else { try { p.Kill(); } catch { } } } catch { } GlobalCounters.numberOfCurrentPrintings += numberOfPages; try { TaskbarManager.HideTaskbar(); } catch { } System.Threading.Thread.Sleep(TimeSpan.FromSeconds(6)); try { TaskbarManager.HideTaskbar(); } catch { } try { this.sender.SendAction("Printed " + numberOfPages + " pages."); } catch { } } else { System.Windows.MessageBox.Show("Unfortunately, you can not print so many pages! Please press OK to continue."); } } catch (Exception ex) { this.log.Info("Exception: " + ex.ToString()); } } //else //{ // System.Windows.MessageBox.Show("Failed to print cause unexptected problem! Please try again.."); //} } /* try * { * KillAdobe("AcroRd32"); * } * catch { }*/ }
private void SendToPrinter(string pdfPath) { ProcessStartInfo info = new ProcessStartInfo(); //print //printto //preview info.Verb = "print"; info.FileName = pdfPath; info.CreateNoWindow = true; info.WindowStyle = ProcessWindowStyle.Hidden; Process p = new Process(); p.StartInfo = info; p.Start(); p.WaitForInputIdle(); System.Threading.Thread.Sleep(3000); if (false == p.CloseMainWindow()) p.Kill(); }
private void SendToPrinter(string pdfPath) { ProcessStartInfo info = new ProcessStartInfo(); info.Verb = "preview"; info.FileName = pdfPath; info.CreateNoWindow = true; info.WindowStyle = ProcessWindowStyle.Hidden; Process p = new Process(); p.StartInfo = info; p.Start(); p.WaitForInputIdle(); System.Threading.Thread.Sleep(3000); if (false == p.CloseMainWindow()) p.Kill(); //PrintDocument pd = new PrintDocument(); //pd.PrintPage += new PrintPageEventHandler(PrintPage); //PrintDialog pdi = new PrintDialog(); //pdi.Document = pd; //if (pdi.ShowDialog() == DialogResult.OK) //{ // pd.Print(); //} //else //{ // MessageBox.Show("Print Cancelled"); //} }
public InvocationResult Invoke() { if (ProcessStartBuilder == null) { throw new InvalidOperationException("You must specifiy a ProcessStartBuilder or don't use an empty contructer"); } var process = ProcessStartBuilder(); process.UseShellExecute = false; process.CreateNoWindow = true; process.RedirectStandardError = true; process.RedirectStandardInput = true; process.RedirectStandardOutput = true; process.WindowStyle = ProcessWindowStyle.Hidden; if (ProcessStartModifier != null) { ProcessStartModifier(process); } var result = new InvocationResult(); try { var proc = new System.Diagnostics.Process(); proc.StartInfo = process; proc.Start(); if (Timeout > 0) { proc.WaitForExit(Timeout); } else { proc.WaitForExit(); } if (proc.HasExited == false) { if (proc.Responding) { proc.CloseMainWindow(); } else { proc.Kill(); } } result.Error = proc.StandardError.ReadToEnd(); result.Output = proc.StandardOutput.ReadToEnd(); proc.Close(); } catch (Exception ex) { result.ExecutionError = ex.Message; } return(result); }
public static void KillProcess(Process process, bool waitForExit, bool closeMainWindow) { try { switch (closeMainWindow) { case true: process.CloseMainWindow(); break; case false: if (!process.HasExited) process.Kill(); break; } } catch (Exception) { TerminateProcess(process.Handle, 0); //Forcibly kill the process } if (waitForExit) process.WaitForExit(); process.Dispose(); }
private static void SendToPrinter(String filename) { var info = new ProcessStartInfo { Verb = "print", FileName = filename, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }; var p = new Process {StartInfo = info}; p.Start(); p.WaitForInputIdle(); Thread.Sleep(3000); if (false == p.CloseMainWindow()) p.Kill(); }
private void timer2_Tick(object sender, EventArgs e) { //------------------------------IF--------------------------------------------------------------------- /* * if (BTC_day_dag > BTC_day_equi) * { * mining_renta = "Dag"; * label_resultat.Text = "faut miner l'ETHER: " + Math.Round((BTC_day_dag * 1000), 3) + " mBTC/day"; * //label_resultat_euro.Text = EUR_by_day_dag + " EUR/day " + (double.Parse(EUR_by_day_dag)) * 30 + "EUR/MONTH"; * } * else * { * mining_renta = "Equi"; * label_resultat.Text = "faut miner le ZCASH: " + Math.Round((BTC_day_equi * 1000), 3) + " mBTC/day"; * //label_resultat_euro.Text = EUR_by_day_equi + " EUR/day " + (double.Parse(EUR_by_day_equi)) * 30 + "EUR/MONTH"; * } */ //--------------------------------------------------------------------------------------------------- if (textBox_dag_link.Text != "" || textBox_equi_link.Text != "") { button2.Enabled = true; if (mining_renta == "Dag" & already_mining != "Dag") { try { timer2.Stop(); proc.CloseMainWindow(); proc.Kill(); proc.Close(); already_mining = "null"; } catch { } already_mining = "Dag"; proc.StartInfo.FileName = textBox_dag_link.Text; proc.Start(); } else if (mining_renta == "Equi" & already_mining != "Equi") { try { timer2.Stop(); proc.CloseMainWindow(); proc.Kill(); proc.Close(); already_mining = "null"; } catch { } already_mining = "Equi"; proc.StartInfo.FileName = textBox_equi_link.Text; proc.Start(); } } else { MessageBox.Show("Entrer lien vers le .bat", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public override bool Process(Tricycle.GameWindow gw) { var settings = Properties.Settings.Default; var key = gw.Keyboard; if (key[settings.NextKey] || StateGlobals.EvaluateGamepad(gw, settings.NextGamePad)) { _selected++; while (StateGlobals.EvaluateGamepad(gw, settings.NextGamePad)) ; } if (key[settings.PrevKey] || StateGlobals.EvaluateGamepad(gw, settings.PrevGamePad)) { _selected--; while (StateGlobals.EvaluateGamepad(gw, settings.PrevGamePad)) ; } if (key[settings.PrevPageKey] || StateGlobals.EvaluateGamepad(gw, settings.PrevPageGamepad)) { _selected -= filesPerPage; while (StateGlobals.EvaluateGamepad(gw, settings.PrevPageGamepad)) ; } if (key[settings.NextPageKey] || StateGlobals.EvaluateGamepad(gw, settings.NextPageGamepad)) { _selected += filesPerPage; while (StateGlobals.EvaluateGamepad(gw, settings.NextPageGamepad)) ; } if (key[settings.SelectKey] || StateGlobals.EvaluateGamepad(gw, settings.SelectGamepadCombo)) { gw.Suspend(); var p = new Process(); p.StartInfo.FileName = settings.EmuPath; p.StartInfo.Arguments = settings.Parameters.Replace("%rom", "\"" + _romList[_selected] + "\""); p.Start(); System.Threading.Thread.Sleep(5000); while (true) { if (gw.Keyboard.GetGlobalKeyState(settings.KillKey) || StateGlobals.EvaluateGamepad(gw, settings.KillGamepadCombo)) { p.CloseMainWindow(); break; } System.Threading.Thread.Sleep(0); } p.Close(); p.Dispose(); gw.Resume(); System.Threading.Thread.Sleep(1000); } _selected = _selected % _romList.Count; if (_selected < 0) { _selected = (maxPages * filesPerPage - (filesPerPage + _selected)) - 1; } return true; }
private static void StartIisExpress() { var startInfo = new ProcessStartInfo { WindowStyle = ProcessWindowStyle.Normal, ErrorDialog = true, LoadUserProfile = true, CreateNoWindow = false, UseShellExecute = false, RedirectStandardInput = true, Arguments = string.Format("/path:\"{0}\" /port:{1}", GetSiteRunningPath, Port) }; var programfiles = string.IsNullOrEmpty(startInfo.EnvironmentVariables["programfiles(x86)"]) ? startInfo.EnvironmentVariables["programfiles"] : startInfo.EnvironmentVariables["programfiles(x86)"]; startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe"; try { _iisProcess = new Process { StartInfo = startInfo }; _iisProcess.Start(); } catch { _iisProcess.CloseMainWindow(); _iisProcess.Dispose(); throw; } }
private static void KillProcess(Process p) { try { p.CloseMainWindow(); p.WaitForExit(100); if (!p.HasExited) { p.Kill(); p.WaitForExit(); } } catch (Exception e) { Logging.LogUsefulException(e); } }
private static void UnloadProcess(Process p) { if (p != null) { if (!p.HasExited) { p.CloseMainWindow(); } p.Dispose(); p = null; } }
public async void onPrintRequested(string selected) { try { this.events.PublishOnUIThread(new ViewStartPrintProgressCommand()); } catch { } System.Threading.Thread.Sleep(2000); if (selected == "before") { // PrinterCanceller.CancelPrint(); string path = System.IO.Path.Combine( System.IO.Path.GetDirectoryName( this.GetType().Assembly.Location), "Printings", GlobalCounters.numberOfCurrentPrintings.ToString() + ".pdf"); var success = await _mainBrowser.PrintToPdfAsync(path, new PdfPrintSettings { MarginType = CefPdfPrintMarginType.Custom, MarginBottom = 10, MarginTop = 0, MarginLeft = 20, MarginRight = 10, }); System.Threading.Thread.Sleep(3000); if (success) { try { iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(path); int numberOfPages = pdfReader.NumberOfPages; if (GlobalCounters.numberOfCurrentPrintings + numberOfPages <= Convert.ToInt32(this.numberOfAvailablePagesToPrint)) { try { this.log.Info("Invoking Action: ViewPrintRequested " + numberOfPages.ToString() + " pages."); } catch { } try { System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(); info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; info.Verb = "print"; info.FileName = path; info.CreateNoWindow = true; System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo = info; p.Start(); p.WaitForExit(); p.CloseMainWindow(); if (false == p.CloseMainWindow()) { try { p.Kill(); } catch { } } else { try { p.Kill(); } catch { } } try { TaskbarManager.HideTaskbar(); } catch { } } catch { } GlobalCounters.numberOfCurrentPrintings += numberOfPages; try { TaskbarManager.HideTaskbar(); } catch { } System.Threading.Thread.Sleep(6000); try { TaskbarManager.HideTaskbar(); } catch { } try { this.sender.SendAction("Printed " + numberOfPages + " pages."); } catch { } } else { System.Windows.MessageBox.Show("Δυστυχώς, δεν μπορείτε να εκτυπώσετε τόσσες σελίδες. Πατήστε OK για να συνεχίσετε."); } } catch (Exception ex) { this.log.Info("Exception: " + ex.ToString()); } } // else //{ // System.Windows.MessageBox.Show("Αποτυχία εκτύπωσης! Παρακαλώ, δοκιμάστε ξανά.."); //} } /* try * { * KillAdobe("AcroRd32"); * } * catch { }*/ }
private void RestartSoftware() { foreach (var process in Process.GetProcessesByName("lcore")) { process.Kill(); } Process process2 = new Process(); // Configure the process using the StartInfo properties. process2.StartInfo.FileName = "C:/Program Files/Logitech Gaming Software/LCore.exe"; process2.StartInfo.Arguments = ""; process2.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; process2.Start(); process2.WaitForExit(5000); process2.CloseMainWindow(); }
void CloseMainWindow(Process proc) { proc.CloseMainWindow(); }
public void Close() { try { if (AgentType == eAgentType.Service) { if (gingerNodeInfo != null) { // this is plugin driver GingerNodeProxy.GingerGrid = WorkSpace.Instance.LocalGingerGrid; GingerNodeProxy.CloseDriver(); gingerNodeInfo.Status = GingerNodeInfo.eStatus.Ready; if (mProcess != null) // it means a new plugin process was started for this agent - so we close it { // Remove the node from the grid WorkSpace.Instance.LocalGingerGrid.NodeList.Remove(gingerNodeInfo); // Close the plugin process mProcess.CloseMainWindow(); } GingerNodeProxy = null; gingerNodeInfo = null; return; } } if (Driver == null) { return; } Driver.IsDriverRunning = false; if (Driver.Dispatcher != null) { Driver.Dispatcher.Invoke(() => { Driver.CloseDriver(); Thread.Sleep(1000); }); } else { Driver.CloseDriver(); } if (MSTATask != null) { // Using cancellation token source to cancel CancelTask = new BackgroundWorker(); CancelTask.DoWork += new DoWorkEventHandler(CancelTMSTATask); CancelTask.RunWorkerAsync(); } Driver = null; } finally { OnPropertyChanged(Fields.Status); OnPropertyChanged(Fields.IsWindowExplorerSupportReady); } }
private void closeWindow(Process proc) { if (proc == null) return; proc.WaitForInputIdle(); proc.Refresh(); if (proc.CloseMainWindow()) { proc.Close(); } try { if (!proc.HasExited) { // didn't send the close message m_log.writeElt("fail"); m_log.writeAttr("close", "message not sent"); m_log.writeAttr("kill", "issued"); m_log.endElt(); proc.Kill(); } } catch (InvalidOperationException){} }