Returning Focus of a "lost" window

Hello,

I am working on a project in which the application will only allow one instance of itself to be running at a time. I have figured this part out but the part that has be stumped is if the instance already running is "lost" (hidden behind another window or minimized or somehow off the screen) to bring it back to the front of the screen. I have tried focus and bringtofront options but those do not seam to work. Thanks for any advice on this.




Answer this question

Returning Focus of a "lost" window

  • tt2lhp

    Hello,

    Have you tried this way: http://msdn2.microsoft.com/en-us/library/ms996475.aspx to force only one instance of the application

    Hope it helps. Thank you



  • Andy Jarvis

    using System;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    using System.Diagnostics;
    using System.Reflection;

    public class OneInstnace
    {
    [STAThread]
    public static void Main()
    {
    //Get the running instance.
    Process instance = RunningInstance();
    if (instance == null)
    {
    //There isn't another instance, show our form.
    Application.Run (new Form());
    }
    else
    {
    //There is another instance of this process.
    HandleRunningInstance(instance);
    }
    }
    public static Process RunningInstance()
    {
    Process current = Process.GetCurrentProcess();
    Process[] processes = Process.GetProcessesByName (current.ProcessName);

    //Loop through the running processes in with the same name
    foreach (Process process in processes)
    {
    //Ignore the current process
    if (process.Id != current.Id)
    {
    //Make sure that the process is running from the exe file.
    if (Assembly.GetExecutingAssembly().Location.Replace( "/", "\\") ==
    current.MainModule.FileName)
    {
    //Return the other process instance.
    return process;
    }
    }
    }

    //No other instance was found, return null.
    return null;
    }


    public static void HandleRunningInstance(Process instance)
    {
    //Make sure the window is not minimized or maximized
    ShowWindowAsync (instance.MainWindowHandle , WS_SHOWNORMAL);

    //Set the real intance to foreground window
    SetForegroundWindow (instance.MainWindowHandle);
    }

    [DllImport("User32.dll")]

    private static extern bool ShowWindowAsync(
    IntPtr hWnd, int cmdShow);
    [DllImport("User32.dll")] private static extern bool
    SetForegroundWindow(IntPtr hWnd);
    private const int WS_SHOWNORMAL = 1;
    }


  • Returning Focus of a "lost" window