Reputation: 48
I'm new to c# and I find it pretty different from my PHP origin, so I may be doing this completely wrong. However from my understanding it's pretty accurate. Basically I need to start a program on button click in my form (that part works perfectly) then when the user closes the program i need to run an action, in this case I'm displaying a message box.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
namespace usb
{
class Applications
{
//condition variables
public static bool CalcStatus = false;
public static void Calc()
{
Process CALC;
CALC = Process.Start("calc.exe");
if (CALC.HasExited)
{
MessageBox.Show("CALC has exited");
CalcStatus = true;
}
}
}
}
this snippet is part of a class, and another class uses this function, when it is called calc will open the box will not pop up with the alert when calc is closed. Does anyone know what I'm doing wrong? Any more pointers are welcome as I'm still learning :)
Upvotes: 1
Views: 528
Reputation: 1527
Approach 1: Show message with wait
//condition variables
public static bool CalcStatus = false;
public static void Calc()
{
var calc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "calc.exe"
}
};
calc.Start();
calc.WaitForExit();
MessageBox.Show("CALC has exited");
CalcStatus = true;
}
Approach 2: Show Message without wait
//condition variables
public static bool CalcStatus = false;
public static void Calc()
{
var calc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "calc.exe"
},
EnableRaisingEvents = true,
};
calc.Exited += calc_Exited;
calc.Start();
CalcStatus = true;
}
static void calc_Exited(object sender, EventArgs e)
{
MessageBox.Show("CALC has exited");
}
Upvotes: 0
Reputation: 203836
You use the Exited
event to run some code when the process exits:
CALC.EnableRaisingEvents = true;
CALC.Exited += (sender, args) => MessageBox.Show("CALC has exited");
Upvotes: 8