I am struggling to figure out why my User Control events are not executing. I have a dynamic UserControl, "MainMenu", within a dynamic UserControl, "MainControl".
In MainMenu I have the following:
public partial class MainMenu : UserControl
{
public MainMenu()
{
InitializeComponent();
///
///Event Subscriptions
///
this.LostFocus += this.MainMenu_LostFocus;
}
public void MainMenu_LostFocus(object sender, EventArgs e)
{
this.Visible = false;
}
}
In MainControl:
public partial class MainControl : UserControl
{
private Custom_UI.MainMenu mainMenu = new Custom_UI.MainMenu();
public MainControl()
{
InitializeComponent();
mainMenu.Visible = false;
mainMenu.BringToFront();
this.Controls.Add(mainMenu);
mainMenu.BringToFront();
}
private void menuButton1_Click(object sender, EventArgs e)
{
if (mainMenu.Visible)
{
mainMenu.Visible = false;
}
else
{
mainMenu.Visible = true;
this.Focus();
}
}
}
And finally the main Form:
public partial class Form1 : Form
{
MainControl mainControl = new MainControl() {
Dock = DockStyle.Fill
};
public Form1()
{
InitializeComponent();
this.Controls.Add(mainControl);
}
}
So basically, the method MainMenu_LostFocus is not being invoked when I click elsewhere on the form. I have also tried using this.MouseLeave instead of this.LostFocus.
Hopefully this I was clear enough and thanks in advance.
OK... lest try another, improved approach. the reason is the fact we don't want to be forced to handle click on each and every control added to
MainControland force it to receive focus. it's just clumsy.We'd also like to encapsulate the whole code in a single control (
MainMenu) - not "must have", but surely "nice to have"this is my new idea:
hope this solution will be better and more usable