
正文
C# Winform防止闪频和再次运行
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
其实想实现只允许运行一个实例很简单,就是从program的入口函数入手。有两种情况:
第一种,用户运行第二个的时候给一个提示:
using System;
using System.Collections.Generic;
using System.Windows.Forms; namespace pm_sjz_gupiao
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
bool flag;
//使用一个指示调用线程是否应拥有互斥体的初始所属权的布尔值、一个作为互斥体名称的字符串、
//一个在方法返回时指示调用线程是否被授予互斥体的初始所属权的布尔变量来初始化一个Mutex实例。
System.Threading.Mutex mutex = new System.Threading.Mutex(true,Application.ProductName,out flag);
if (flag)
{
//启用应用程序的可视样式
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//处理当前在消息队列中所有windows消息
// Form1为你程序的主窗体,如果是控制台程序不用这句
Application.DoEvents();
Application.Run(new login());//http://weili.ooopic.com/weili_1130951.html //释放 Mutex 一次
mutex.ReleaseMutex();
}
else
{
MessageBox.Show(null, "咨询通已经在运行,\n\n这个程序即将退出!", "咨询通 提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Application.Exit();
} }
}
}
第二种,用户运行第二个实例的时候激活第一个实例。
这种是提示用户的最好方法,当之前打开的程序最小化或者处于其他状态或者没有焦点时,使用这种方法可以让用户注意到之前的程序。
//方法二:禁止多个进程运行,并当重复运行时激活以前的进程 using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection; namespace HelloCsharp
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
//获取当然应用程序的实例
Process instance = RunningInstance();
if (instance == null)
{
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.DoEvents();
System.Windows.Forms.Application.Run(new Form1());
}
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;
}
public static void HandleRunningInstance(Process instance)
{
//将窗体置于正常的显示模式
ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
//将窗体显示在最上层
SetForegroundWindow(instance.MainWindowHandle);
}
[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;
}
}






