Comment puis-je focaliser une fenêtre étrangère?

J'ai une application qui ne peut avoir qu'une seule instance de lui-même ouvert à la fois. Pour appliquer cela, j'utilise ce code:

        System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
        System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
        foreach (System.Diagnostics.Process p in myProcesses)
        {
            if (p.ProcessName == me.ProcessName)
                if (p.Id != me.Id)
                {
                    //if already running, abort this copy.
                    return;
                }
        }
        //launch the application.
        //...

Il fonctionne très bien. J'aimerais aussi qu'il soit capable de se concentrer à la forme de la déjà en cours d'exécution exemplaire. C'est, avant de revenir, je veux amener de l'autre instance de l'application au premier plan.

Comment dois-je faire?

Re: SetForeGroundWindow:

SetForeGroundWindow œuvres, à un point:

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    public static extern bool SetForegroundWindow(IntPtr hWnd); 

    //...
                if (p.Id != me.Id)
                {
                    //if already running, focus it, and then abort this copy.
                    SetForegroundWindow(p.MainWindowHandle);
                    return;
                }
    //...

Ce n'mettre la fenêtre au premier plan si elle n'est pas réduite. Génial.
Si la fenêtre EST réduite, cependant, il reste réduite.

Il a besoin d'onu-minimiser.

Solution via SwitchToThisWindow (qui Fonctionne!):

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

    [STAThread]
    static void Main()
    {
        System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
        System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(me.ProcessName);
        foreach (System.Diagnostics.Process p in myProcesses)
        {
            if (p.Id != me.Id)
            {
                SwitchToThisWindow(p.MainWindowHandle, true);
                return;
            }
        }
        //now go ahead and start our application ;-)

source d'informationauteur Jude Allred | 2009-01-14