How to GetForegroundWindow From Path Program

248 Views Asked by At

When I use Process.Start(Path); Sometimes the program does not appear in the foreground, but it does appear in the taskbar To solve this problem, I must use the "AutoItX" reference to show the program in the foreground using GetForegroundWindow(), But how can I get GetForegroundWindow using Path? ("C:/Users/.../name_program/")

Update

my question is how can I get GetForegroundWindow From Path.

I appreciate any help, thank you

1

There are 1 best solutions below

4
Marco On BEST ANSWER

I can't test it, but it should work:

private const int ALT = 0xA4;
private const int EXTENDEDKEY = 0x1;
private const int KEYUP = 0x2;
private const int SHOW_MAXIMIZED = 3;

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

public static void ActivateWindow(IntPtr mainWindowHandle)
{
    // Guard: check if window already has focus.
    if (mainWindowHandle == GetForegroundWindow()) return;

    // Show window maximized.
    ShowWindow(mainWindowHandle, SHOW_MAXIMIZED);
            
    // Simulate an "ALT" key press.
    keybd_event((byte)ALT, 0x45, EXTENDEDKEY | 0, 0);
                        
    // Simulate an "ALT" key release.
    keybd_event((byte)ALT, 0x45, EXTENDEDKEY | KEYUP, 0);

    // Show window in forground.
    SetForegroundWindow(mainWindowHandle);
}

With this you can create the process and then activate it:

var proc = Process.Start(path);
proc.WaitForInputIdle();
ActivateWindow(proc.MainWindowHandle);