C#唯一进程封装
C# 唯一性进程的方法封装
csharp
public class UniqueProcess
{
/// <summary>
/// 焦点切换指定的窗口,并将其带到前台
/// </summary>
/// <param name="hWnd"></param>
/// <param name="fAltTab"></param>
[DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
//提示消息
public static string Message = "该应用系统已经在运行!";
/// <summary>
/// 获取当前程序名已运行的进程,如果没有则返回null
/// </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)
{
return process;
}
}
return null;
}
/// <summary>
/// 将进程主窗体显示到最前
/// </summary>
/// <param name="instance"></param>
public static void HandleRunningInstance(Process instance)
{
MessageBox.Show(Message, "提示信息");
IntPtr handle = instance.MainWindowHandle;
//将进程显示在最前
SwitchToThisWindow(handle, true);
}
}
在WPF中使用
csharp
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
var instance = UniqueProcess.RunningInstance();
if (instance != null)
{
UniqueProcess.HandleRunningInstance(instance);
//关闭
Application.Current.Shutdown();
return;
}
//正常启动
base.OnStartup(e);
}
}
在Winform中使用
csharp
internal static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
var instance = UniqueProcess.RunningInstance();
if (instance != null)
{
UniqueProcess.HandleRunningInstance(instance);
//未创建窗体,直接返回就退出程序了,无需另外关闭
return;
}
//正常启动
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}