How to bring app to front, if already open?

Hussnain Fareed 20 Reputation points
2024-05-22T13:25:34.1033333+00:00

How to bring the app to front, if already open?

My app is Windows Form application c#

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,865 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,500 questions
{count} votes

Accepted answer
  1. KOZ6.0 6,130 Reputation points
    2024-05-22T23:47:49+00:00

    I've rewritten my answer.Thank you, for Viorel.

    (1) Create a class containing Pinvoke declarations.

    using System.Runtime.InteropServices;
    
    internal class NativeMethods
    {
        public const int HWND_BROADCAST = 0xffff;
    
        public static int WM_WAKEUP_WINDOW = 
            RegisterWindowMessage("{28D5B089-B46F-4F69-99BE-6525596547E6}");
    
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern bool PostMessage(IntPtr hWnd, int Msg,
                                              IntPtr wParam, IntPtr lParam);
    
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int RegisterWindowMessage(string lpString);
    
        [DllImport("User32")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
    }
    

    (2) Program.cs

    using System.Diagnostics;
    using System.Threading;
    
    internal static class Program
    {
        [STAThread]
        static void Main() {
            var current = Process.GetCurrentProcess();
            var mutex = new Mutex(true, current.ProcessName, out bool createdNew); ;
            if (createdNew) {
                try {
                    ApplicationConfiguration.Initialize();
                    Application.Run(new Form1());
                } finally {
                    mutex.ReleaseMutex();
                }
            } else {
                NativeMethods.PostMessage(
                    NativeMethods.HWND_BROADCAST, 
                            NativeMethods.WM_WAKEUP_WINDOW,
                            IntPtr.Zero, IntPtr.Zero);
            }
        }
    }
    

    (3) Form

    protected override void WndProc(ref Message m) { 
        if (m.Msg == NativeMethods.WM_WAKEUP_WINDOW) {
            notifyIcon1.Visible = false;
            WindowState = FormWindowState.Normal;
            Show();
            NativeMethods.SetForegroundWindow(Handle);
            return;
        }
        base.WndProc(ref m);
    }
    

0 additional answers

Sort by: Most helpful