unity防止应用双开,检测进程是否运行中
来源:华佗健康网
直接上代码,调用CheckStartupIsRepeated()方法,若进程已经打开,则自身关闭
using System;
using System.Runtime.InteropServices;
using UnityEngine;
public class PreventDuplicateLaunch
{
private const uint TH32CS_SNAPPROCESS = 0x00000002;
private const int MAX_PATH = 260;
[StructLayout(LayoutKind.Sequential)]
private struct PROCESSENTRY32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
public string szExeFile;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
public static void CheckStartupIsRepeated()
{
if (IsDuplicateProcessRunning())
{
ShowDuplicateLaunchWarning();
Application.Quit();
}
}
private static bool IsDuplicateProcessRunning()
{
IntPtr snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == IntPtr.Zero)
{
Debug.LogError("Failed to create snapshot of processes.");
return false;
}
PROCESSENTRY32 processEntry = new PROCESSENTRY32 { dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32)) };
if (!Process32First(snapshot, ref processEntry))
{
CloseHandle(snapshot);
return false;
}
string currentProcessName = $"{Application.productName}.exe";
int processCount = 0;
do
{
if (processEntry.szExeFile.Equals(currentProcessName, StringComparison.OrdinalIgnoreCase))
{
processCount++;
if (processCount > 1)
{
CloseHandle(snapshot);
return true;
}
}
}
while (Process32Next(snapshot, ref processEntry));
CloseHandle(snapshot);
return false;
}
private static void ShowDuplicateLaunchWarning()
{
MessageBox(IntPtr.Zero, "当前进程已经运行,请勿重复启动。", "Warning", 0x00000030);
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容