仅允许该程序的一个实例时,从系统托盘恢复窗口

Pea*_*lyk 4 c# winapi

好吧,标题很长,应该告诉我面临的问题.

这是最小化图标托盘时的代码:

void MainFormResize(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.ShowInTaskbar = false;
            }
        }
Run Code Online (Sandbox Code Playgroud)

当程序已经打开并且在sys托盘中时,仍然有人想要打开它的另一个实例,那么:

    private static void Main(string[] args)
            {
                bool createdNew = true;
                using (Mutex mutex = new Mutex(true, "IPADcommunicator", 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)
                            {
                                IntPtr handle = FindWindow(null,"IPADcommunicator");
                                SetForegroundWindow(handle);
                                ShowWindow(handle,5);

                                break;
                            }
                        }
...
Run Code Online (Sandbox Code Playgroud)

但是,它不能正常工作.主窗口没有恢复.我已经google了很多,并没有找到解决这个问题的方法.提前致谢!

Han*_*ant 6

在不可见的窗口上调用SetForegroundWindow()是行不通的.还有许多其他可能的失败模式,当您开始传递null时,FindWindow()是一个可悲的失败模式.

不要自己发明,.NET已经为单实例应用程序提供了很好的内置支持.您甚至可以在第二个副本启动并通过命令行时收到通知.这就是你想要的,只需恢复窗口而不是破解API.你需要的代码在这里.