How can I use several forms for the general menu in a Winforms application?

I have an existing .NET Winforms application created using several complex forms, and

1) all forms live throughout the life of the application, and

2) only one form is displayed at a time (user switches between forms)

I need these forms to share a common menu that will be handled by a single business logic controller. (The visible form is also constantly updated by the controller)

Is there a way in the same menu that appears at the top of each form and has a menu handled by their common controller, without having to make it an MDI application?

Many thanks!

+3
source share
3 answers

Create a basic form using the menu. Individual forms can then inherit this basic form, automatically getting the same menu. To reorganize existing forms, edit form.cs and change

 public partial class Form1 : Form 

to

 public partial class Form1 : MyBaseForm
+4
source

Create a menu in a user control (user control), and then add this control to each of your forms.

+1
source

, , .

:

: , .

static class FormService{
    /*
     * Members
     */
    private static Dictionary<string, Form> _forms = new Dictionary<string, Form>();
    private static Dictionary<string, Type> _types = new Dictionary<string, Type>();       
    private static Form opened_ = null;

    /*
     * Properties
     */

    public static Form Opened

    /*
     * Methods
     */
    public static void register(string className, Type type){
        if (_types.ContainsKey(className))throw new Exception("Form already registered");
        _forms.Add(className, Activator.CreateInstance(type));
        _types.Add(className, type);

    }

    // use with Convert.ChangeType
    public static Type getFormType(string className){
        return _types[className];
    }

    public static void open(string className){
        if (opened_ != null){
            opened_.Hide();
        }
        opened_ = _forms[className];
        opened_.ShowDialog(); // show dialog will block main menu actions
    }

}
0

Source: https://habr.com/ru/post/1727286/


All Articles