我有一个应用程序,当再次启动时会检测是否已经有相同名称的进程在运行,如果有,则激活正在运行的应用程序窗口,然后退出。
问题是主窗口可能被隐藏(只显示通知区域图标),因此我没有窗口句柄。
在启动时,上一个实例的 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;
}
}
}
}
}
}