1、第一种情况: 最小化+托盘
public App()
{
this.Startup += App_Startup;
}
private void App_Startup(object sender, StartupEventArgs e)
{
bool ret;
mutex = new System.Threading.Mutex(true, "RsVPN", out ret);
if (!ret)
{
int hWnd = FindWindow(null, "RsVPN");
int id = -1;
IntPtr p = new IntPtr(hWnd);
GetWindowThreadProcessId(p, out id);
ShowWindow(p, 9);
SetForegroundWindow(p);
Environment.Exit(-1);
}
//or
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
string str = current.ProcessName + "::" + current.Id.ToString();
if (process.Id != current.Id)
{
int hWnd = FindWindow(null, "RsVPN");
IntPtr p = new IntPtr(hWnd);
ShowWindowAsync(p, WS_SHOWNORMAL); //显示
SetForegroundWindow(p);//放到前端
Environment.Exit(-1);
}
}
//or
Process[] p = Process.GetProcessesByName("RsVPN");
if (p.Length > 0)
{
IntPtr handle = FindWindowByCaption(IntPtr.Zero, p[0].ProcessName);
ShowWindowAsync(handle, 9);
SetForegroundWindow(handle);
Environment.Exit(-1);
}
}
主窗口中处理
private void button_close_Click(object sender, RoutedEventArgs e)
{
e.Handled = true;
this.WindowState = WindowState.Minimized;
}
1、第二种情况: 最小化 + 隐藏+托盘
主窗口中添加事件
private void MainWindow_StateChanged(object sender, EventArgs e)
{
if (this.WindowState == WindowState.Minimized)
{
this.Hide();
}
if (this.WindowState == WindowState.Normal)
{
this.Show();
}
}