0

I have WPF allocation and I want to be able to open only one instance of my application.

So i have this 2 classes:

public sealed class SingleInstance
    {
        public static bool AlreadyRunning()
        {
            bool running = false;
            try
            {
                // Getting collection of process  
                Process currentProcess = Process.GetCurrentProcess();

                // Check with other process already running   
                foreach (var p in Process.GetProcesses())
                {
                    if (p.Id != currentProcess.Id) // Check running process   
                    {
                        if (p.ProcessName.Equals(currentProcess.ProcessName) == true)
                        {
                            running = true;
                            IntPtr hFound = p.MainWindowHandle;
                            if (User32API.IsIconic(hFound)) // If application is in ICONIC mode then  
                                User32API.ShowWindow(hFound, User32API.SW_RESTORE);
                            User32API.SetForegroundWindow(hFound); // Activate the window, if process is already running  
                            break;
                        }
                    }
                }
            }
            catch { }
            return running;
        }
    }

And:

public class User32API
    {
        [DllImport("User32.dll")]
        public static extern bool IsIconic(IntPtr hWnd);

        [DllImport("User32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("User32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        public const int SW_RESTORE = 9;
    }

App.xaml:

protected override void OnStartup(StartupEventArgs e)
{
    if (SingleInstance.AlreadyRunning())
        App.Current.Shutdown(); // Just shutdown the current application,if any instance found.  

    base.OnStartup(e);
}

So with this solution only one instance is allow but in case the user try to open another instance i can see that in the task bar i have new icon of my application, this icon automatically close when the mouse is over but I want to prevent this icon to be show so I remove this from App.xaml:

StartupUri="MainWindow.xaml"

And now my application not started (probably started but i cannot see it). Any chance to achieve what I want ?

I need to call MainWindow but I don't know from where

UPDATE

So I try this approach:

protected override void OnStartup(StartupEventArgs e)
        {
            if (SingleInstance.AlreadyRunning())
                App.Current.Shutdown(); // Just shutdown the current application,if any instance found.  

            base.OnStartup(e);
            new MainWindow().Show();
        }

And still i can see the second (and third and so...) icons when the user try to open another instance

user1860934
  • 417
  • 2
  • 9
  • 22

0 Answers0