JustMe.77 JustMe.77 - 3 years ago 129
C# Question

How can I keep the state of a boolean across button clicks?

I'm trying to write a program that can be used to launch another program. I have a button, and when it's clicked, I'd like to start a program, and also record that the program has been launched. When I go to start a new program, I'd like to first check that I haven't already started the program—and if I have, close the existing instance first (so at most one instance of the program will exist at a time).

I've already written the following code:

private void button1_Click(object sender, EventArgs e)
bool status = false;
if (status != true)
status = true;

Now my problem is, if I click on the button, the variable is set to
as you can see on the first line. How I can do it correctly? Also, how I do return 0 if status is set on true?

Answer Source

Move the declaration of the bool variable outside the method if you would like to preserve its value across invocations:

bool status = false;
Process myProcess;
private void button1_Click(object sender, EventArgs e) {
    if (status != true) {
        myProcess = new Process()
        myProcess.EnableRaisingEvents = true;
        status = true;
        // Start a process to print a file and raise an event when done.
        myProcess.StartInfo.FileName = "C:\\Users\\David\\Desktop\\Test\\Test.exe";
        myProcess.Exited += new EventHandler(Process_Exited);

private void Process_Exited(object sender, System.EventArgs e) {
    status = false;

Now the diagnostic message will come up only once per life time of your object. Once the process exits, the status is reset to false, letting you click the button again.

Also note that since the button does not do anything after the status is set to true, it is a good idea to disable it to avoid confusing end-users.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download