开发者

Restoring window from the system tray when allowing only one instance of that program

ok, the title is pretty long and should tell the problem i'm facing with.

Here is the code when minimizing to icon tray:

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

When the program is already opened and in sys tray, and still someone wants to open another instance of it, then:

    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);

                            开发者_JS百科    break;
                            }
                        }
...

Howeve, it is not working properly. The mainwindow is not restored. I've googled a lot and haven't found solutions for that problem. Thanks in advance!


Calling SetForegroundWindow() on an invisible window isn't going to work. There are many other possible failure mode, FindWindow() is a miserable one when you start passing null.

Don't invent this yourself, .NET already has great built-in support for single instance apps. You can even get a notification when a 2nd copy starts and pass the command line. Which is what you want here, simply restore the window instead of hacking the API. The code you need is here.


After looking through dozens of solutions including the link from Hans, I do not believe that the accepted answer's link will restore an app from the systray. All it seems to be doing is correctly managing a single instance and passing arguments to the single instance.

A more complete solution which was able to manage single instance, restore a minimised window and restore a systray window can be found on codeplex here. http://www.codeproject.com/KB/cs/SingleInstanceAppMutex.aspx

It's also extremely simple to incorporate into your own code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜