Reputation: 192
i want to use one MainMenuStrip across all open Forms in my application. I don't want to display the same MainMenu on all forms, instead the MainMenu should only appear on my MainForm and should be accessible from all my other Forms.
The desired behaviour is the same as in Visual Studio 2013 (probably other versions do it the same way). If one document is floation and you hit the ALT button or any combination e.g. ALT+F, the MainWindow comes to front and the MainMenu is visible although the MainWindow does not get activated it seems. When you hit the ALT button again, focus is returned to the floating Window.
I tried forwarding the messages from a sibling form to the MainForm when the Menu-Key is hit but the MainForm needs to be the Foreground window to process the message - as i can see in the .net sourcecode. https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/ToolStripManager.cs,1680
I don't want to use MDI - i just wish to have the same Menu behavior as in MDI.
If anyone has any suggestions on how to achieve this i will be very thankfull.
Upvotes: 0
Views: 668
Reputation: 21969
If you want to mimic behavior of VS, then here is a way.
static class Program
{
static Form _main;
static Form _previous;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// simulate some environment here
_main = new Form1();
_main.FormClosed += (s, e) => Application.Exit();
_main.Show();
new Form2 { Text = "1" }.Show();
new Form2 { Text = "2" }.Show();
new Form2 { Text = "3" }.Show();
Application.Run();
}
public static void MenuOpen(Form form)
{
_main.Activate();
_previous = form;
_main.MainMenuStrip.MenuDeactivate += MainMenuStrip_MenuDeactivate;
_main.MainMenuStrip.Show();
}
static void MainMenuStrip_MenuDeactivate(object sender, EventArgs e)
{
_main.MainMenuStrip.MenuDeactivate -= MainMenuStrip_MenuDeactivate;
_previous.Activate();
_previous.Focus();
}
}
Form1
is any form with MainMenuStrip
defined (aka main form), when form is closed application ends.
In Form2
all you need is to handle menu keypress, one possibility - is preview key down event handler (don't forget to set KeyPreview=true
):
void Form2_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.Alt)
Program.MenuOpen(this);
}
Demo:
Upvotes: 1