winform,同个程序只允许启动一次
Posted 0x0c,0x0d
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了winform,同个程序只允许启动一次相关的知识,希望对你有一定的参考价值。
static class Program { [DllImport("User32.dll")] private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow); [DllImport("User32.dll")] private static extern bool SetForegroundWindow(System.IntPtr hWnd); /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { bool createNew; using (System.Threading.Mutex m = new System.Threading.Mutex(true, Application.ProductName, out createNew)) { if (createNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Main()); } else { MessageBox.Show("Only one instance of this application is allowed!"); Process current = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName(current.ProcessName); //遍历与当前进程名称相同的进程列表 foreach (Process process in processes) { //如果实例已经存在则忽略当前进程 if (process.Id != current.Id) { //保证要打开的进程同已经存在的进程来自同一文件路径 if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName) { ShowWindowAsync(process.MainWindowHandle, 1); //调用api函数,正常显示窗口 SetForegroundWindow(process.MainWindowHandle); //将窗口放置最前端 } } } } } } }
以上是关于winform,同个程序只允许启动一次的主要内容,如果未能解决你的问题,请参考以下文章
Reload Activity 以在 Fragment 之间重新切换