Create a gist now

Instantly share code, notes, and snippets.

c# run program on background with inline event handler.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using System.ComponentModel;
namespace TestProject
{
class runner
{
string appPath;
int timeOut = 5000;
public event EventHandler proc_finished = delegate { };
public runner(string ap)
{
this.appPath = ap;
}
public void orntotxt(string input, string output)
{
var bw = new BackgroundWorker();
bw.DoWork += (sender, args) => {
Process proc = new Process();
proc.StartInfo.FileName = appPath + "\\test.exe";
proc.StartInfo.Arguments = "/a " + input + " " + output;
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc.Start();
Thread.Sleep(1000);
proc.WaitForExit(timeOut);
if (proc.HasExited == false)
if (proc.Responding)
proc.CloseMainWindow();
else
proc.Kill();
};
bw.RunWorkerCompleted += (sender, args) => {
if (args.Error != null) { }
this.proc_finished(this, new EventArgs());
};
bw.RunWorkerAsync();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
namespace TestProject
{
public partial class TestMain: Form
{
string appPath = "C:\\";
public TestMain()
{
InitializeComponent();
}
private void TestMain_Load(object sender, EventArgs e)
{
appPath = Path.GetDirectoryName(Application.ExecutablePath);
}
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Running...";
runner rn = new runner(appPath);
rn.proc_finished += delegate {
textbox1.AppendText("Result Text");
button1.Text = "Runned!";
};
rn.orntotxt("Args1", "Args2");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment