简体   繁体   中英

Bring another application to front

I have built a C# Windows Form application. When the form loads, it's full screen. The form has icons on it that launch other applications (not forms). I'm trying to accomplish determining whether the application is already running or not and if it's not, start it, otherwise bring it to the front. I have accomplished determining whether the application is running or not and if it's not, to start it, I just can't figure out how to bring it to the front if it is. I have read other results on Google and Stack Overflow, but haven't been able to get them to work.

Any help is greatly appreciated!

My code, so far, is:

private void button4_Click(object sender, EventArgs e)
{
    Process[] processName = Process.GetProcessesByName("ProgramName");
    if (processName.Length == 0)
    {
        //Start application here
        Process.Start("C:\\bin\\ProgramName.exe");
    }
    else
    {
        //Set foreground window
        ?
    }
}
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr handle);

private IntPtr handle;

private void button4_Click(object sender, EventArgs e)
{
    Process[] processName = Process.GetProcessesByName("ProgramName");
    if (processName.Length == 0)
    {
        //Start application here
        Process.Start("C:\\bin\\ProgramName.exe");
    }
    else
    {
        //Set foreground window
        handle = processName[0].MainWindowHandle;
        SetForegroundWindow(handle);
    }
}

If you also wish to show the window even if it is minimized, use:

if (IsIconic(handle))
    ShowWindow(handle, SW_RESTORE);

Although several answers here are marked as working, they did not work in my case. I found correct code, which worked for me on blog of Joseph Gozlan . I'm repeating here this awesome code for convenience. Notice slight but very important difference with async call, compared to other answers. All credits to original code author.

[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr WindowHandle);
public const int SW_RESTORE = 9;
    
private void FocusProcess(string procName)
{
  Process[] objProcesses = System.Diagnostics.Process.GetProcessesByName(procName); 
  if (objProcesses.Length > 0)
  {
    IntPtr hWnd = IntPtr.Zero;
    hWnd = objProcesses[0].MainWindowHandle;
    ShowWindowAsync(new HandleRef(null,hWnd), SW_RESTORE);
    SetForegroundWindow(objProcesses[0].MainWindowHandle);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM