I have an application with a panel control that uses dynamically generated buttons to start programs....an application launcher if you will. The buttons are created at run time and assigned a generic event handler that fires off a "Process.Start()" when clicked. it works fine:(App and _app are just ways to provide which buttons the user has available from a database. In this case ALL buttons are available so there are no tricks)
foreach (App _application in _app)
{
_application.ApplicationSecurities = _appSecurities;
_application.LoginInfo = _info;
Button _but = new Button();
_but.Font = new Font(FontFamily.GenericSerif, 21, FontStyle.Bold);
_but.Height = FontHeight + 80;
_but.Text = _application.ButtonText;
_but.Tag = _application;
_but.Click += Button_Click;
_but.Dock = DockStyle.Top;
string _workingDirectory = Path.Combine(@"C:\Blah\", _application.ExecutableName);
string _appPath = Path.Combine(_workingDirectory, _application.LatestVersion);
_but.ToolTip = _application.LatestVersion;
_buttons.Add(_but);
PnlControls.Controls.Add(_but);
}
The problem is, When The user clicks a button, I would like the buttons on the panel to disappear which I do with a
PnlControls.Controls.Clear();
They DO disappear, but if i click around on the panel (which is still up), the application that was represented by that buttons location still fires off a click event and launches when the application closes! I have tried various methods to remove the event handlers from that panel,then repopulate the buttons when the application closes. Heres the latest iteration of the "DisableAllButtons" function:
private void DisableAllButtons()
{
foreach (Button _but in _buttons)
{
PnlControls.Controls.Remove(_but);
_but.Click -= null;
_but.Dispose();
}
_buttons.Clear();
}
Heres how the process start and above function are called (from within the click event)
private void LaunchApplication(App appToRun) { string _workingDirectory = Path.Combine(@"C:\Blah\", appToRun.ExecutableName);
string _appPath = Path.Combine(_workingDirectory, appToRun.LatestVersion);
try
{
string _start = Path.Combine(_appPath, appToRun.ExecutableName) + ".exe";
Process _proc = new Process();
_proc.StartInfo.FileName = _start;
_proc.StartInfo.Arguments = appToRun.StartingArguments;
DisableAllButtons();
_proc.Start();
_proc.WaitForExit();
CreateButtons();
}
catch (Exception _e)
{
MessageWindow.Show(@"Failed to start application", _e.Message);
}
}
Why are these buttons firing after they have been removed?