Created
February 14, 2023 07:16
-
-
Save rqx110/285aa839fff2ce644b3d5141946e599a to your computer and use it in GitHub Desktop.
限制一次只能打开一个程序
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal static class ProcessManager | |
{ | |
public static void GetProcessLock() | |
{ | |
ProcessManager.ProcessLock = new Mutex(false, "Global\\LuYao.Toolkit[" + ProcessManager.GetUid() + "]", ref ProcessManager.HasLock); | |
if (!ProcessManager.HasLock) | |
{ | |
ProcessManager.ActiveWindow(); | |
Environment.Exit(0); | |
} | |
} | |
private static string GetUid() | |
{ | |
byte[] array = Encoding.UTF8.GetBytes(Assembly.GetExecutingAssembly().Location); | |
using (MD5 md = MD5.Create()) | |
{ | |
array = md.ComputeHash(array); | |
} | |
return BitConverter.ToString(array); | |
} | |
public static void ActiveWindow() | |
{ | |
using (Process currentProcess = Process.GetCurrentProcess()) | |
{ | |
foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName)) | |
{ | |
if (process.MainModule.FileName == currentProcess.MainModule.FileName) | |
{ | |
ProcessManager.SwitchToThisWindow(process.MainWindowHandle, true); | |
break; | |
} | |
} | |
} | |
} | |
public static void ReleaseLock() | |
{ | |
if (ProcessManager.ProcessLock != null && ProcessManager.HasLock) | |
{ | |
ProcessManager.ProcessLock.Dispose(); | |
ProcessManager.HasLock = false; | |
} | |
} | |
[DllImport("user32.dll")] | |
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab); | |
private static Mutex ProcessLock; | |
private static bool HasLock; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.coderbusy.com/archives/2837.html