返回信息流很多单机程序,需要以singleton方式打开,
比如main.exe,第一次点击main.exe,打开main.exe,
当main.exe打开后,再次点击main.exe,不会再启动main.exe,而是切换到先前打开的main.exe
上述功能,可以通过以下方式实现:
------------
//Program.cs
------------
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Globalization;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
namespace singelton.process
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Process instance = GetRunningProcess();
try
{
if (null == instance)
{
Application.Run(new MaimForm());
}
else
{
ShowWindowAsync(instance.MainWindowHandle, WS_MAXIMIZE);
SetForegroundWindow(instance.MainWindowHandle);
}
}
catch (Exception ex)
{
//
}
}
/// <summary>
/// Gets the current running process.
/// </summary>
/// <returns></returns>
public static Process GetRunningProcess()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
foreach (Process process in processes)
{
if (process.Id != current.Id)
{
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
{ return process; }
}
}
return null;
}
public const int WS_MAXIMIZE = 3;
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
}
}
这是一条镜像帖。来源:北邮人论坛 / dot-net / #2082同步于 2010/7/7
该镜像源已超过 30 天没有更新,可能在源站已被删除。
dotNET机器人发帖
抛砖引玉之 process singleton
ahomer
2010/7/7镜像同步4 回复
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "2F7C55CF-23F9-4318-B50D-33F11EF53EA5", out createdNew))
{
if (createdNew)
{
Application.Run(new MainFrm());
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
if (Assembly.GetExecutingAssembly().Location == current.MainModule.FileName)
{
ShowWindowAsync(process.MainWindowHandle, SW_RESTORE);
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}