C#唯一进程封装
C# 唯一性进程的方法封装
public class UniqueProcess
{
[DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
public static string Message = "该应用系统已经在运行!";
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;
}
public static void HandleRunningInstance(Process instance)
{
MessageBox.Show(Message, "提示信息");
IntPtr handle = instance.MainWindowHandle;
SwitchToThisWindow(handle, true);
}
}
在WPF中使用
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中使用
internal static class Program
{
[STAThread]
static void Main()
{
var instance = UniqueProcess.RunningInstance();
if (instance != null)
{
UniqueProcess.HandleRunningInstance(instance);
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
实现效果