需求: 一个程序在后台运行(即隐藏了窗体), 如果再次点击该程序对应的exe时,不启动新进程,而是显示出原告已运行的程序窗体。
平台环境: .net
代码如下:
//添加引用
using System.Diagnostics;
using System.Runtime.InteropServices;
[MTAThread]
static void Main()
{
///获取原先已运行的进程
Process instance = null ;
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName (current.ProcessName);
foreach (Process process in processes)
{
//排除当前进程
if (process.Id != current.Id)
{
instance = process;
break;
}
}
if (instance == null)
{
//没有运行的进程
Application.Run(new Form());
}
else
{
//已有运行的进程,显示其主窗体
ShowWindowAsync(instance.MainWindowHandle, 1);
SetForegroundWindow(instance.MainWindowHandle);
}
}
[DllImport("User32.dll ")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll ")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
----------------------------------------------------------------------------------