c#设计应用程序单实例运行
利用WindowsFormsApplicationBase的IsSingleInstance来控制应用程序只能单实例运行。
[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> /// 应用程序的主入口点。 /// </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(); } }
单实例的类中有一个变量ApplicationContext,应用程序线程的上下文,这个变量是为了切换窗口而设计的。具体实现代码看下面的ChangeForm。
调用时,例如上面的Form5中有一个按钮,打开新窗口Form6,则:
private void button1_Click(object sender, EventArgs e) { Program.ShowForm(new Form6()); }
只需要这样调用就能够切换窗口,关闭Form5,节约资源。