简体   繁体   中英

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();        
}

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");
    }
}

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