static
class
Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static
void
Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(
false
);
Process instance = RunningInstance();
if
(instance ==
null
)
{
Application.Run(
new
frmMain());
}
else
{
HandleRunningInstance(instance);
}
}
#region 确保程序只运行一个实例
private
static
Process RunningInstance()
{
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
;
}
private
static
void
HandleRunningInstance(Process instance)
{
ShowWindowAsync(instance.MainWindowHandle, 1);
SetForegroundWindow(instance.MainWindowHandle);
}
[DllImport(
"User32.dll"
)]
private
static
extern
bool
ShowWindowAsync(System.IntPtr hWnd,
int
cmdShow);
[DllImport(
"User32.dll"
)]
private
static
extern
bool
SetForegroundWindow(System.IntPtr hWnd);
#endregion
}
转载 http://www.jb51.net/article/82124.htm