1

I made a simple winforms application and it contains a single form. The problem is when I click the executable I want the activated form to get focused instead of multiple instances of the application. I tried to solve this problem this way. This only prevents multiple instances, but can't get focus on the activated form. This code is from Program.cs file.

namespace Shutdown_Scheduler
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            string processName = Process.GetCurrentProcess().ProcessName;
            Process[] processCollection = Process.GetProcessesByName(processName);
            if (processCollection.Length > 1)
            {
                Process.GetCurrentProcess().Kill();
                ProgramEntry();
            }
            else
            { 
                ProgramEntry();
            }
        }
        static void ProgramEntry()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}
Endre Both
  • 5,540
  • 1
  • 26
  • 31
  • this thread should help you https://stackoverflow.com/questions/2315561/correct-way-in-net-to-switch-the-focus-to-another-application – Denis Schaf Apr 23 '19 at 08:25
  • you can enable Bring to top property of the form so it will have the focus. – SH7 Apr 23 '19 at 10:05
  • See here: [Run the current application as Single Instance and show the previous instance](https://stackoverflow.com/a/50555532/7444103). My answer there may seem convoluted, but it allows to activate a single instance of an app even if the its window is minimized or hidden (plus, i wanted to show an UI Automation way :). For a simplified method, see Hans Passant's comment. It points to one of his answers on this matter: [SetForegroundWindow not working](https://stackoverflow.com/a/29260770/7444103). – Jimi Apr 23 '19 at 12:24

0 Answers0