转:限制应用程序运行一次并激活已经运行的程序 .
转载自:http://blog.csdn.net/zhxingway/article/details/5288662
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;
}
}

浙公网安备 33010602011771号