天天看點

限制應用程式運作一次并激活已經運作的程式

C#單執行個體運作實作

在某些情況我們要求應用程式隻能運作一次,後運作的執行個體要把之前運作的程式激活并自己退出。

現在是代碼,找了好久哦,大家給點掌聲吧,呵呵 .

關鍵詞:winform限制主程式運作一次,激活程式,我是直接把我項目中Program.cs中的代碼Copy過來了,希望大家不要見怪.

static class Program

{

// Uses to active the exist window

[DllImport("User32.dll")]

public static extern void SetForegroundWindow(IntPtr hwnd);

[DllImport("User32.dll")]

private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

// 0-Hidden, 1-Centered, 2-Minimized, 3-Maximized

private const int WS_SHOWNORMAL = 1;

/// <summary>

/// 應用程式的主入口點。

/// </summary>

[STAThread]

static void Main()

{

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

//限制程式隻打開一次

if (RunningInstance() == null)

{

Application.Run(new Form1());

}

//Application.Run(new RecordQuery());

}

/// <summary>

/// 限制程式隻打開一次

/// </summary>

/// <returns></returns>

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.

ShowWindowAsync(process.MainWindowHandle, WS_SHOWNORMAL);

SetForegroundWindow(process.MainWindowHandle);

return process;

}

}

}

//No other instance was found, return null.

return null;

}

}

繼續閱讀