0

I have an application that minimizes to icon state when user press close. I want to make application show again when user tries to open the app, instead of just opening the app again.

I thought of using settings: A boolean value, true if the app is opened and false if it isn't but that would mean you should set it to false when user closes app and true in the load function. But since close event doesn't run when program crashes, that would make program un-openable (:D?), and i have no idea how to call events between two programs.

TL;DR: Show the app to user instead of opening it twice when user opens program again, just like Discord.

Thanks!

LIM10
  • 5
  • 1
  • 1
  • 2
    Typically done either using a `Mutex` and or the `Process` way. Does this answer your question [What is the correct way to create a single-instance WPF application?](https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-wpf-application)? Although tagged with `WPF` it's the same. [Here's another solution](https://stackoverflow.com/questions/34617940/single-instance-of-an-app-in-c-sharp) that may help as well. – Trevor Mar 11 '21 at 14:48

1 Answers1

0

In your Program class add the ShowWindow method from the User32 dll:

const int SW_SHOW = 5;

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);

Then write that in your main method before calling the Application.Run method:

var currentProcess = System.Diagnostics.Process.GetCurrentProcess();

// search for another process with the same name
var anotherProcess = System.Diagnostics.Process.GetProcesses().FirstOrDefault(p => p.ProcessName == currentProcess.ProcessName && p.Id != currentProcess.Id);

if (anotherProcess != null)
{
    ShowWindow(anotherProcess.MainWindowHandle, SW_SHOW);
    return; // don't continue to run your application.
}

UPDATE:

The con of that way is that you're not actually identify your program, you're just searching for a process with the same name. so when renaming the exe file you will be able to run an another process of the same program with a different name. or if there is another program in your PC with the same name you will find it as was your program so you will show it instead of yours.

KBar
  • 50
  • 6