【问题标题】:Restoring window from the system tray when allowing only one instance of that program仅允许该程序的一个实例时从系统托盘恢复窗口
【发布时间】:2011-01-04 10:59:26
【问题描述】:

好的,标题很长,应该能说明我面临的问题。

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

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

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

    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;
                            }
                        }
...

但是,它无法正常工作。主窗口未恢复。 我用谷歌搜索了很多,但没有找到解决该问题的方法。 提前致谢!

【问题讨论】:

    标签: c# winapi


    【解决方案1】:

    在不可见的窗口上调用 SetForegroundWindow() 是行不通的。还有很多其他可能的失败模式,FindWindow()在你开始传null的时候就惨了。

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

    【讨论】:

      【解决方案2】:

      在查看了包括 Hans 的链接在内的数十种解决方案后,我认为接受的答案的链接不会从系统托盘中恢复应用程序。它似乎所做的只是正确管理单个实例并将参数传递给单个实例。

      可以在此处的 codeplex 上找到更完整的解决方案,该解决方案能够管理单个实例、恢复最小化窗口和恢复系统托盘窗口。 http://www.codeproject.com/KB/cs/SingleInstanceAppMutex.aspx

      将其合并到您自己的代码中也非常简单。

      【讨论】:

        猜你喜欢
        • 2010-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-21
        相关资源
        最近更新 更多