Brothers In Code

...a serious misallocation of .net resources

Conditionally Opening a Modal Form in a Parent Form's Activate Event

In a Winforms App, I wanted to see if a local configuration file existed, and if it didn't I wanted to force the user into the setup form after being prompted to do so.  I basically had the following code in my main form:

private void MainForm_Activated(object sender, EventArgs e)
{
  //if no config has been loaded...
  if (SaveData.Current.ScannerConfigId == 0)
  {
    DialogResult result = MessageBox.Show(
      "No local configuration was found.  Press OK to select a configuration.  Press Cancel to exit.",
      "Setup",
      MessageBoxButtons.OKCancel);
    if (result == DialogResult.OK)
    {
      //...then force the user into the setup form
      Form form = new SetupForm();
      form.Owner = this;
      form.ShowDialog();
    }
    else
      Application.Exit();

  }
}

Unfortunately, I found that upon clicking 'OK' to close the MessageBox, the activate event was fired again before completing the first one that opened the MessageBox.  To fix it I just added a simple semaphore:

private void MainForm_Activated(object sender, EventArgs e)
{
  if (!checkingConfig)
  {
    //if no config has been loaded...
    if (SaveData.Current.ScannerConfigId == 0)
    {
      checkingConfig = true;
      DialogResult result = MessageBox.Show(
        "No local configuration was found.  Press OK to select a configuration.  Press Cancel to exit.",
        "Setup",
        MessageBoxButtons.OKCancel);
      checkingConfig = false;
      if (result == DialogResult.OK)
      {
        //...then force the user into the setup form
        Form form = new SetupForm();
        form.Owner = this;
        form.ShowDialog();
      }
      else
        Application.Exit();

    }
  }
}

After that, the second call quickly exited allowing the first to pick up where it left off.

Loading