How to take up vertical space for a programmatically added menu?

I am adding a MenuStrip to my form, and I would like to add other controls below it, as usual, Point (0, 0) in the upper left corner of the empty space of the form. After I add a menu to my form and add more controls, they overlap. So I want to pick up some height of the client rectangle for the menu, and the c button Location = (0,0)should be CORRECT under the menu.

How to do it?

If I assign the MainMenu property to the Menu of the form, it does it automatically, but I really want and should use the MenuStrip.


Edit: this does not work:
MenuStrip menu = new MenuStrip();
menu.Items.Add("File");
menu.AutoSize = false;
menu.Height = 50;
menu.Dock = DockStyle.Top;
MainMenuStrip = menu;
Controls.Add(menu);

Button b = new Button();
b.Text = "hello world";
b.SetBounds(0, 25, 128, 50);
Controls.Add(b);

While this works, as if I would like to do it with MenuStrip:

Menu = new MainMenu();
Menu.MenuItems.Add("File");

Button b = new Button();
b.Text = "hello world";
b.SetBounds(0, 0, 128, 50);
Controls.Add(b);
+5
2

SetBounds(0, 25, 128, 50), b.Top 25 ( ). menu, :

b.SetBounds(0, menu.Bottom, 128, 50);

[]

:

public partial class Form1 : Form
{
    private int menuStripHeight = 50;

    public Form1()
    {
        InitializeComponent();
        this.ControlAdded += Form1_ControlAdded;

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        MenuStrip menu = new MenuStrip();
        menu.Items.Add("File");
        menu.AutoSize = false;
        menu.Height = menuStripHeight; ;
        menu.Dock = DockStyle.Top;
        MainMenuStrip = menu;
        Controls.Add(menu);

        Button b = new Button();
        b.Text = "hello world";

        // note that the position used is 0,0
        b.SetBounds(0, 0, 128, 50);

        Controls.Add(b);
    }

    void Form1_ControlAdded(object sender, ControlEventArgs e)
    {
        if (e.Control.GetType().FullName != "System.Windows.Forms.MenuStrip")
            e.Control.Top += menuStripHeight;
    }
}

[ 2]

Panel:

MenuStrip menu = new MenuStrip();
menu.Items.Add("File");
menu.AutoSize = false;
menu.Height = menuStripHeight; ;
menu.Dock = DockStyle.Top;
MainMenuStrip = menu;
Controls.Add(menu);

Panel p = new Panel();
p.SetBounds(0, menuStripHeight, this.Width, this.Height);
Controls.Add(p);

Button b = new Button();
b.Text = "hello world";
p.Controls.Add(b);
b.SetBounds(0, 0, 128, 50);
+1

DockStyle.Top MenuStrip, Panel, . Dock = Top , . , :

MenuStrip menu = new MenuStrip() {
  AutoSize = false,
  Dock = DockStyle.Top
};
menu.Items.Add("File");

Panel p = new Panel(){
   Dock = DockStyle.Top
};

Controls.Add(p);
Controls.Add(menu);
MainMenuStrip = menu;

Button b = new Button(){
  Text = "hello world"
};
p.Controls.Add(b);
b.SetBounds(0, 0, 128, 50);
+1

All Articles