Search code examples
c#processfocusparent-childsetforegroundwindow

c# Giving focus back to parent form from other app


I'm trying to start and .exe from a child form of my main app, but the issue is that when I open the other .exe and it finish it's work (scan a finger print) and exit, my app gets minimized, so I try this:

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd); 


    void method {
    ..........more code...........
     using (Process proc = new Process())
                    {
                        proc.StartInfo.FileName = "WindowsFormsApplication3.exe";
                        proc.Start();
                        SetForegroundWindow(proc.MainWindowHandle);
                    }
    ............code here..............
    }

but it doesnt work, my main app lost the focus, I find many solutions but any of them work for me, the other .exe is an app that I'm doing too.


Solution

  • If you want to active finger print window, your code is right! but add a waiting before SetForegroundWindow... like this:

    while (string.IsNullOrEmpty(proc.MainWindowTitle))
    {
        System.Threading.Thread.Sleep(100);
        proc.Refresh();
    }
    

    and, If you want to active the caller form (main app) you don't need SetForegroundWindow! You can write:

    while (string.IsNullOrEmpty(proc.MainWindowTitle))
    {
        System.Threading.Thread.Sleep(100);
        proc.Refresh();
    }
    // Then active caller form...
    this.Activate();
    

    Anyway, you need wait until finger-print window shown...