WinForm 应用程序禁止多个进程运行
2013-07-30 13:47
495 查看
方法一: 禁止多个进程运行
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace 开启新的进程 { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { bool flag; System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out flag); if (flag) { // 启用应用程序的可视样式 Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // 处理当前在消息队列中的所有 Windows 消息 Application.DoEvents(); Application.Run(new Form1()); // 释放 System.Threading.Mutex 一次 mutex.ReleaseMutex(); } else { MessageBox.Show(null, "相同的程序已经在运行了,请不要同时运行多个程序!\n\n这个程序即将退出!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); Application.Exit(); } } } } 方法二: 禁止多个进程运行,并当重复运行时激活以前的进程
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; namespace 开启新的进程 { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { System.Diagnostics.Process instance = RunningInstance(); if (instance == null) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { HandleRunningInstance(instance); } } /// <summary> /// 获取当前正在运行的进程实例 /// </summary> /// <returns></returns> public static Process RunningInstance() { // 获取当前活动的进程 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) { return process; } } } // 如果没有其他同名进程存在,则返回 null return null; } // 指示该属性化方法由非托管动态链接库 (DLL) 作为静态入口点公开 [DllImport("User32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); [DllImport("User32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); private const int WS_SHOWNORMAL = 1; /// <summary> /// 如果有另一个同名进程启动,则调用之前的实例 /// </summary> /// <param name="instance"></param> private static void HandleRunningInstance(Process instance) { // 确保窗体不是最小化或者最大化 ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); // 将之前启动的进程实例弄到前台窗口 SetForegroundWindow(instance.MainWindowHandle); } } }
相关文章推荐
- WinForm 应用程序禁止多个进程运行
- WinForm 应用程序禁止多个进程运行
- 禁止系统运行某个进程的简单方法
- C#禁止应用程序同时运行的方法
- Web(浏览器)打开运行WinForm应用程序
- C#程序双击运行之后,界面不显示,但是在任务管理器有进程(一个winform找bug之旅)
- VC小技巧(1)---禁止同一应用程序同时运行
- C# winform 禁止程序运行
- 如何使用进程名禁止程序运行两个实例
- 运行时错误 说明: 服务器上出现应用程序错误。此应用程序的当前自定义错误设置禁止远程查看应用程序错误的
- 转C# 只能运行一个winForm进程
- C#、VS2012 Winform程序解决方案名称更改后报错“调试器无法继续运行该进程。调用的目标发生了异常。”
- 怎样才能在C#桌面应用程序(winform)中调用运行EXE文件?
- VB.NET禁止同一用户启动相同的进程(同一进程允许多个用户运行情况下)
- C#禁止应用程序的多重运行
- 禁止多个进程运行
- 再谈应用程序单例运行(只能开启一个进程)
- C# 只能运行一个WinForm进程
- C#禁止应用程序的多重运行