【发布时间】:2010-12-19 03:48:35
【问题描述】:
我有一个应用程序,它在随后启动时检测是否有同名的进程已经在运行,如果是,则激活正在运行的应用程序的窗口,然后退出。
问题是主窗口可能被隐藏(只有一个通知区域图标可见),因此我没有窗口句柄。
在启动时,前一个实例的MainWindowHandle 属性为0,所以我无法发送ShowWindow 或PostMessage。
有什么方法可以发送一条可以被正在运行的应用程序拦截的消息,从而允许它显示其主窗口?
应用程序是用 C# 编写的,下面是我用来实现此目的的代码。
[STAThread]
static void Main()
{
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "MyMutexName", out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
Interop.WINDOWINFO pwi = new Interop.WINDOWINFO();
IntPtr handle = process.MainWindowHandle;
var isVisible = Interop.GetWindowInfo(handle, ref pwi);
if (!isVisible)
{
MessageBox.Show(Constants.APP_NAME + " is already running, check the notification area (near the clock).",
Constants.APP_NAME, MessageBoxButtons.OK, MessageBoxIcon.Information);//temporary message, until I find the solution
//Interop.ShowWindow(handle, Interop.WindowShowStyle.ShowNormal);
//Interop.PostMessage(handle, Interop.WM_CUSTOM_ACTIVATEAPP, IntPtr.Zero, IntPtr.Zero);
}
else
Interop.SetForegroundWindow(handle);//this works when the window is visible
break;
}
}
}
}
}
}
【问题讨论】: