將 Form 的動態選單代碼移至獨立 .cs 類別時,this.Hide()、this.Controls.Add 等報錯,因為 this 不再是 Form 實例。
public static class MenuBuilder {
public static void Build(Form host) {
var menu = new MenuStrip();
var itemFile = new ToolStripMenuItem("檔案");
menu.Items.Add(itemFile);
host.Controls.Add(menu); // 使用 host 而非 this
host.MainMenuStrip = menu;
}
}
// Form 中呼叫
MenuBuilder.Build(this);
itemFile.Click += (s, e) => {
var frm = new SubForm();
frm.Show();
host.Hide(); // 隱藏主視窗
};