Use the issingleinstance of windowsformsapplicationbase to control that an application can only run on a single instance.
[Dllimport ("user32.dll", entrypoint = "showwindow", charset = charset. auto)] public static extern int showwindow (intptr hwnd, int ncmdshow); [dllimport ("user32.dll")] Private Static extern bool setforegroundwindow (intptr hwnd); static singleinstancemanager manager; /// <summary> /// main entry point of the application. /// </Summary> [stathread] Static void main (string [] ARGs) {application. enablevisualstyles (); application. setcompatibletextrenderingdefault (false); Manager = new singleinstancemanager (New form5 (); manager. run (ARGs);} public static void showform (Form nform, bool closeoldone = true) {manager. changeform (nform, closeoldone);} public class singleinstancemanager: windowsformsapplicationbase {applicationcontext app; Public singleinstancemanager (Form mainform) {This. issingleinstance = true; APP = new applicationcontext (); app. mainform = mainform;} protected override bool onstartup (Microsoft. visualBasic. applicationservices. startupeventargs e) {application. run (APP); return false;} protected override void onstartupnextinstance (startupnextinstanceeventargs eventargs) {base. onstartupnextinstance (eventargs); setforegroundwindow (App. mainform. handle); showwindow (App. mainform. handle, 4);} public void changeform (Form newform, bool closeoldone = true) {If (App. mainform = newform) return; form TEM = app. mainform; TEM. hide (); app. mainform = newform; newform. show (); If (closeoldone) TEM. close ();}}
The single-instance class has a variable applicationcontext, the context of the application thread. This variable is designed to switch the window. For the specific implementation code, see the changeform below.
During the call, for example, if there is a button in form5 above and the new window form6 is opened, then:
private void button1_Click(object sender, EventArgs e){ Program.ShowForm(new Form6());}
In this way, you can switch the window and close form5 to save resources.
C # design an application to run a single instance