限制一个form被同时打开的数量 Limite The Number of Forms Opened at the same time


There is a kind of forms that you only want to show 1 instance for users, because multi instances is unnecessary and may cause concurrency problems. To achieve this, I tried in several ways:

1. Bad practise: Make the form a singleton class, however, it's not the solution. Because once you closed it, the singleton object will be disposed, then if you try to open it again by call the Show() method, an exception will be thrown said:"Cannot access a disposed object Form_Name"...

2. Actually, the easiest way is just show the form as a model dialog, by using the ShowDialog() method. Since a form is usually launched by an event from UI components(such as button click or menu item click), set the form to model will prevent user launch the same form once again before they closing the current one. However, the cons are also apparent: users are prevented from doing any operations on the parent forms, this may make them feel quite inconvenient.

3. Another solution is just use singleton patter, but hide the form other than close it when user try to close it, this can be implemented by cancel the Form_Closing event.

 

原文地址:https://www.cnblogs.com/k330/p/1060649.html