让C#程序只运行一个实例,显示已经运行的界面
2012-07-12 08:21
465 查看
让程序只运行一个实例的方法一:
static void Main()
{System.Threading.Mutex mutex;
bool isNew;
mutex = new System.Threading.Mutex(true, "myproject", out isNew);
if (isNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
}
else
{
MessageBox.Show("本程序已经在运行!","提示信息",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
}
让程序只运行一个实例的方法二(会显示正在运行的窗口):
static void Main()
{Process instance = RunningInstance();
if (instance == null)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
}
else
{
HandleRunningInstance(instance);
}
}
//返回正在运行的程序进程
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;
}
}
}
return null;//第一次运行,返回null
}
//显示正在运行的进程当前窗口
public static void HandleRunningInstance(Process instance)
{ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //置窗口为正常状态
SetForegroundWindow(instance.MainWindowHandle);
}
#region调用系统api
[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;
#endregion
相关文章推荐
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- C# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- C# WinForm 判断程序是否已经在运行,且只允许运行一个实例,附源码
- C#winform判断程序已经运,且只能运行一个实例
- C#如何判断我的程序已经有一个实例正在运行
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- C#程序双击运行之后,界面不显示,但是在任务管理器有进程(一个winform找bug之旅)
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- C# 显示已经运行程序的主界面
- C#应用程序只允许运行一个实例,多次运行的时候激活当前实例,显示其界面
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- c# 程序只能运行一次(多次运行只能打开同一个程序) 并激活第一个实例,使其获得焦点,并在最前端显示.
- C# WinForm 判断程序是否已经在运行,且只允许运行一个实例,附源码
- C#仅允许一个程序实例运行
- 解决C#程序只允许运行一个实例的几种方法详解
- WinForm判断程序是否已经在运行,且只允许运行一个实例
- C#程序只允许运行一个实例的解决方案
- c# 控制职能运行单一实例,再次运行显示已经运行的实例