retrodrone
retrodrone

Reputation: 5920

Issues with launching a remote process from C#

I'm using System.Diagnostics.Process.Start to launch a remote application on another domain machine.

Unfortunately, if the remote process is already running, but in the background of the remote machine's desktop, the application does not gain focus using Process.Start.

Question 1: Is there another API or mechanism to force the remote application to gain focus, or flash to get the user's attention?

The other issue I noticed, is if the remote process is already running, a new instance may be executed in addition to the original. This violates MSDN's documentation which says:

"If the process is already running, no additional process resource is started. Instead, the existing process resource is reused and no new Process component is created. In such a case, instead of returning a new Process component, Start returns null to the calling procedure."

Question 2: Has anyone found a way to prevent a second instance of the application from launching in this case? Is WMI a better choice to use for remote launching of applications?

Upvotes: 3

Views: 372

Answers (1)

Jess
Jess

Reputation: 8700

Well, don't know how well this will work for you, but it is an example class that you could use in the helper program. This is only the start, if you plan on using it, you will need a networking system (not to bad with C# though). Tell me how it works for you.

/// <summary>
/// Allows you to start a specified program, or if it is already running, bring it into focus
/// </summary>
static class SFProgram
{
    static public void StartFocus(string FileName, string ProcessName)
    {
        if (!ProcessStarted(ProcessName))
            Process.Start(FileName);
        else
            SFProgram.BringWindowToTop("notepad");
    }

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);
    [DllImport("user32.dll")]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    /// <summary>
    /// Bring specified process to focus
    /// </summary>
    /// <param name="windowName">Process Name</param>
    /// <returns>If it was successful</returns>
    private static bool BringWindowToTop(string windowName)
    {
        Process[] processes = Process.GetProcessesByName(windowName);
        foreach (Process p in processes)
        {
            int hWnd = (int)p.MainWindowHandle;
            if (hWnd != 0)
            {
                return SetForegroundWindow((IntPtr)hWnd);
            }
            //p.CloseMainWindow();
        }
        return false;
    }

    private static bool ProcessStarted(string ProcessName)
    {
        Process[] processes = Process.GetProcessesByName(ProcessName);
        return (processes.Length > 0);
    }
}

Upvotes: 2

Related Questions