JustMe.77
JustMe.77

Reputation: 19

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;
        System.Diagnostics.Process.Start("C:\\Users\\David\\Desktop\\Test\\Test.exe");
    }
}

Now my problem is, if I click on the button, the variable is set to false 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?

Upvotes: 2

Views: 833

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726589

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);
        myProcess.Start();
    }
}

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.

Upvotes: 1

The problem is that you are declaring the variable inside the click_button event, so the variable cannot be reached outside the method "click_button"

Try with something like this

bool status = false;
int ChangeStatus()
{
    if(status!=true)
    {
        status = true;
        System.Diagnostics.Process.Start("C:\\Users\\David\\Desktop\\Test\\Test.exe");
        return 0;
    }
  return 1; //if the status is false it will return 1 or the value you want
}

Then in the Button_Click event you should add

 private void button1_Click(object sender, EventArgs e) {
     //I don't know where you will display or save the value (0 or 1) I will assign it in a variable
    var result = ChangeStatus();
 }

Hope it could help you

Upvotes: 0

Related Questions