techy
techy

Reputation: 73

C# console application bring process to foreground

With the following C# console application code, I am able to run the process in background using Jenkins. But now I want to see this process in foreground. What wrong I am doing here ?

[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr handle);
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool ShowWindow(IntPtr handle, int nCmdShow);
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool IsIconic(IntPtr handle);

private void startT32app()
{
    IntPtr handle;
    try
    {
        Console.WriteLine("T32 launching");
        string path = @"C:\T32\bin\windows64\t32mppc.exe";
        string args = @"C:\T32\config.t32";
        ProcessStartInfo procInfo = new ProcessStartInfo(path, args);
        procInfo.CreateNoWindow = false;
        procInfo.UseShellExecute = true;
        procInfo.WindowStyle = ProcessWindowStyle.Normal;

        Process procRun = Process.Start(procInfo);
        handle = procRun.MainWindowHandle;
        SetForegroundWindow(handle);
    }
    catch
    {
        Console.WriteLine("Failed to launch T32");
    }
}
static void Main(string[] args)
{ 
    Program Beginapps = new Program();
    Beginapps.startT32app();        
}

Upvotes: 5

Views: 6073

Answers (1)

M. Schena
M. Schena

Reputation: 2107

An option to achieve your task is to send shift + tab to the window to set it in front of everything (i tried in another application different ways, but only this worked for me):

// is used to set window in front
[DllImport("User32.dll", SetLastError = true)]
static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

public void startT32app()
{
    IntPtr handle;
    try
    {
        Console.WriteLine("T32 launching");
        string path = @"C:\T32\bin\windows64\t32mppc.exe";
        string args = @"C:\T32\config.t32";
        ProcessStartInfo procInfo = new ProcessStartInfo(path, args);
        procInfo.CreateNoWindow = false;
        procInfo.UseShellExecute = true;
        procInfo.WindowStyle = ProcessWindowStyle.Normal;

        Process procRun = Process.Start(procInfo);
        handle = procRun.MainWindowHandle;
        SwitchToThisWindow(handle, true);
    }
    catch
    {
        Console.WriteLine("Failed to launch T32");
    }
}

Upvotes: 6

Related Questions