Question

The app I am creating includes a notify icon and it is in a way that stays active in the background (well, sort of). The problem is that when the user clicks on the icon of my app, the app will launch again, and so I have two notification icons and two activities in the background and two of everything. And if the user clicks the icon again, there will be three of all those things and...... so somehow I should stop this. I have kind of an idea of setting a flag and setting its value to registry, and when my app wants to start, in the form load event, by reading the value, terminates the app. But I want a more... professional way to deal with it. For example not being started at all.

Était-ce utile?

La solution

this is from this answer which is a duplicate of this one. You check in your app's entry constructor for whether or not the app is already running.

static void Main() 
{
    Process currentProcess = Process.GetCurrentProcess();
    var runningProcess = (from process in Process.GetProcesses()
                          where
                            process.Id != currentProcess.Id &&
                            process.ProcessName.Equals(
                              currentProcess.ProcessName,
                              StringComparison.Ordinal)
                          select process).FirstOrDefault();
    if (runningProcess != null)
    {
        ShowWindow(runningProcess.MainWindowHandle, SW_SHOWMAXIMIZED);
       return; 
    }
}

Autres conseils

create some form of Global Mutex/Event handle that your app creates and then in your open routine check for it being present, if it is, exit the startup routing.

I have some basic code here in this answer I gave (for a different issue), but it demonstrates what you are trying to do.

UnauthorizedAccessException on Openexisting global mutex

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top