Ensure that only one instance is running

zhaozj2021-02-16  123

[C #]

Public Static Process RunningInstance ()

{

Process Current = process.getcurrentProcess ();

Process [] processes = process.getProcesSbyName (current.ProcessName);

// Loop through the running processs in with the Same Name

Foreach (Process Process In Processes)

{

// ignore the current process

IF (Process.id! = Current.ID)

{

// Make Sure That The Process Is Running from The Exe File.

IF (Assembly.GetexecutingAssembly (). Location.Replace ("/", "//") == current.mainmodule.FileName)

{

// Return the Other process instance.

Return Process;

}

}

}

// no Other instance was found, return null.

Return NULL;

}

[Vb.net]

Public Shared Function RunningInstance () AS Process

DIM CURRENT AS Process = process.getcurrentProcess ()

DIM process.GetProcessesbyName (Current.ProcessName)

'Loop through the running processs in with the same name

Dim Process as process

For Each Process in Processes

'Ignore the current process

IF process.id <> current.id THEN

'Make Sure That The Process Is Running from The Exe File.

IF [assembly] .getexecutingassembly (). Location.replace ("/", "/") = current.mainmodule.FileName Then

'Return The Other Process Instance.

Return Process

END IF

END IF

Next process

'NO Other Instance Was Found, Return Null.

Return Nothing

End function 'RunningInstance

If an existing form instance is detected, this instance is displayed in the reference:

[STAThread] static void Main () {// Get the running instance Process instance = RunningInstance ();.. If (instance == null) {// There is not another instance, show our form Application.Run (new Form2 ());} else {// There is another instance of this process HandleRunningInstance (instance);.}} public static Process runningInstance () {Process current = Process.GetCurrentProcess (); Process [] processes = Process.GetProcessesByName (current .ProcessName); // Loop through the running processes in with the same name foreach (Process process in processes) {// Ignore the current process if (process.Id = current.Id) {// Make sure that the process is! Running from the exe file. if (assembly.getexecutingassembly (). location.replace ("/", "//") == current.mainmodule.FileName) { // Return the other process instance return process;.}}} // No other instance was found, return null return null;.} Public static void HandleRunningInstance (Process instance) {// Make sure the window is not minimized or maximized ShowWindowAsync (instance.MainWindowHandle, WS_SHOWNORMAL); // Set the real intance to foreground window SetForegroundWindow (instance.MainWindowHandle);} [DllImport ( "User32.dll")] private static extern bool ShowWindowAsync (IntPtr hWnd, int cmdShow); [DllImport ("User32.dll"

)] private static extern bool setForegroundWindow; private const INT WS_SHOWNORMAL = 1 Source: http://blog.9cbs.net/acewang/archive/2004/02/05/17627.aspx

转载请注明原文地址:https://www.9cbs.com/read-14028.html

New Post(0)