Restoring a window from the system tray when only one instance of this program is resolved

ok, the title is quite long and should report a problem that I am facing.

Here is the code that is minimized for the icon:

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

When the program is already open in the sys tray, and still someone wants to open another instance, 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); break; } } ... 

Be that as it may, it does not work properly. The main window is not restored. I googled a lot and did not find solutions to this problem. Thanks in advance!

+4
source share
2 answers

Calling SetForegroundWindow () on an invisible window will not work. There are many other possible failure modes, FindWindow () is pathetic when you start passing zero.

Don't invent it yourself, .NET already has great built-in support for single-instance applications. You can even get a notification when the second copy starts and the command line is transmitted. Here you want to simply restore the window instead of hacking the API. The code you need is here .

+6
source

Looking through dozens of solutions, including a link from Hans, I don’t believe that the accepted return link will restore the application from systray. It all seems to be managing one instance correctly and passing arguments to one instance.

A more complete solution that could manage a single instance, restore a minimized window and restore a systray window can be found here in the code. http://www.codeproject.com/KB/cs/SingleInstanceAppMutex.aspx

It is also very simple to include in your own code.

+1
source

Source: https://habr.com/ru/post/1334189/


All Articles