0

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

ATM
  • 40
  • 5

1 Answers1

1

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);
Marco
  • 56,740
  • 14
  • 129
  • 152
  • there is Error : System.NullReferenceException: 'An object reference is not set to an instance of an object.' proc was null. not first time happen with me – ATM May 09 '22 at 22:26
  • pardon, but `proc` is the process you run, it's `null` if it's not executed! Are you sure you run an existing application? – Marco May 10 '22 at 05:35
  • yes mate, i tested and i treid to write this : ```MessageBox.Show(proc.MainWindowHandle);``` to give me the handle name or title but messagebox showed me null message, you can test your code, and thank you for your help – ATM May 11 '22 at 09:27
  • 1
    Thanks @Marco , My question was not fully answered. But you gave me a hint where to find the solution – ATM Jun 06 '22 at 13:10