C# console application bring process to foreground

自闭症网瘾萝莉.ら 提交于 2020-05-29 09:10:46

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/46974192/c-sharp-console-application-bring-process-to-foreground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!