-1

I have this code to run an exe, catch the hWnd, and move it inside a panel of my C# app.

All is ok, but this process must be restarted every hour, and when I do this by killing it and restarting it, it takes the active focus.

If I am writing something in another app, or watching a video in fullscreen, it causing me to exit fullscreen, or me to write inside this new process instead of Word or whatever...

How I can avoid the launched exe from taking focus when restarted?

[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

[DllImport("user32.dll", SetLastError = true)]
internal static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);

Funzioni.HWnd = IntPtr.Zero;
PSI = new ProcessStartInfo(Funzioni.AppPath)
{
    CreateNoWindow = true,
    RedirectStandardInput = false,
    RedirectStandardOutput = false,
    RedirectStandardError = false
};

P = Process.Start(PSI);

int MaxCount = 10000;
int Count = 0;

while (Funzioni.HWnd == IntPtr.Zero || Count > MaxCount)
{
    P.WaitForInputIdle();
    P.Refresh();
    Funzioni.HWnd = P.MainWindowHandle;
    Count++;
}

if (Funzioni.HWnd == IntPtr.Zero) throw new ApplicationException("The process is taking long to start");

Funzioni.SetParent(Funzioni.HWnd, Pnl_Centrale.Handle);

Funzioni.MoveWindow(Funzioni.HWnd, Funzioni.ExePosX, Funzioni.ExePosY, Funzioni.ExeLarghezza, Funzioni.ExeAltezza - Funzioni.AltezzaToolBar, true);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Tyler
  • 416
  • 4
  • 11
  • 3
    [Is it legal to have a cross-process parent/child or owner/owned window relationship?](https://devblogs.microsoft.com/oldnewthing/20130412-00/?p=4683) Besides, [WaitForInputIdle waits for any thread, which might not be the thread you care about](https://devblogs.microsoft.com/oldnewthing/20100326-00/?p=14483). Plus, `MainWindowHandle` is a lie. It's a made-up concept that doesn't exist. One can only speculate where .NET would be if its library had been written by competent Windows developers. – IInspectable Sep 11 '22 at 06:34
  • 1
    Like everyone else that asks this question, cross process parenting isn't something with which you can have any expectations of good outcomes. Whatever your goal really is, cross process parenting is almost certainly not helpful. – David Heffernan Sep 11 '22 at 07:46
  • Why you both talk about legal stuffs? I am new in C#, i can't figure out most basic things how i can just imagine to code bank-robbery-app? It's just an app that run my other 3 apps inside it. I am perplexed... – Tyler Sep 11 '22 at 12:43
  • Did you read the Raymond Chen article? – David Heffernan Sep 11 '22 at 13:52
  • @DavidHeffernan yes and i figured out how to solve one of the problem. The start a process hidden, then show the window. But the second problem (and also still the main one) is that also in this way i lost the focus on every process restart. If i'm writing on Word and the C# app restart the nested process , cause me to write inside it, instead of Word. If i watch YouTube in fullscreen, cause me to exit. THIS is what i want to solve, considering the app restart the exe every 60 mins. – Tyler Sep 11 '22 at 14:49
  • 1
    If you need a background service, write a [service](https://learn.microsoft.com/en-us/windows/win32/services/services). That's guaranteed to not interfere with your interactive session. Though, restarting a program every *x* minutes sounds like an anti-pattern in itself. Why not keep the app running, and set a timer to do *something* every *x* minutes? – IInspectable Sep 11 '22 at 15:39
  • What we are trying to tell you is that your expectations of cross process parenting are unrealistic – David Heffernan Sep 11 '22 at 16:55
  • @IInspectable no because i need to see what's happen in the other apps, there are 3 that must cycle every hour, and i need to see them for monitoring. So i need the GUI. I can't let open all 3 of them at the same time, that's why the cycle kill-restart for 1 hour each. But i don't want to be "bothered" at each restart. My question is this, if there is a way to not lost the focus my session. No need off-topic suggestions, thanks. – Tyler Sep 11 '22 at 17:25

2 Answers2

0

The ProcessStartInfo properties you are setting only applies to console applications. For a GUI application you must set the ProcessStartInfo.WindowStyle property to Hidden.

It is possible that this will change how MainWindowHandle works because Win32 does not actually have a main window concept. You probably have to p/invoke FindWindow or EnumWindows+GetWindowThreadProcessId.

Anders
  • 97,548
  • 12
  • 110
  • 164
  • Already tried with `ProcessStartInfo.WindowStyle = hidden` but at this point, the second exe will not go inside the first one, considering this can't find the `MainWindowHandle`. I'm familiar with `FindWindow` and i will try it right now, but the other 2 functions are far for me (i am pretty new in C#). There are any example out there? – Tyler Sep 11 '22 at 12:39
  • I looked around regard `GetWindowThreadProcessId` and i solved by getting the Handle by the Thread. But this didn't have solved the main problem (that I thought he did) that is to say i lost the focus on my current app (Word, YouTube in fullscreen, etc.) and the nested exe got it. The C# app restart the nested process every 60 mins, and every 60 mins i lost the focus on the current app i am using (whatever is). – Tyler Sep 11 '22 at 14:57
  • In the EnumWindows callback, check the window title and or class name to see if it matches the window you are interested in. If it matches, call GetWindowThreadProcessId to make sure the process id matches the process you just started. You now have your window and you can call SetParent and ShowWindow... – Anders Sep 11 '22 at 17:30
  • Yes i did that already, now is working. But the lost focus part is still a mystery. On every restart (in the second monitor) i lost the focus of the app that i'm using (in the first monitor) – Tyler Sep 11 '22 at 18:56
  • 1
    @Tyler the Win32 `CreateProcess()` API allows you to specify the `SW_SHOWNOACTIVATE` or `WS_SHOWNA` window style to request the new process show its main window without giving it focus. But the C# `Process.Start()` API does not let you set that style. So, try PInvoking to `CreateProcess()` and see if it solves your problem. – Remy Lebeau Sep 11 '22 at 21:20
  • @Tyler Are you losing focus with `ProcessStartInfo.WindowStyle = Hidden` ? – Anders Sep 11 '22 at 21:23
  • @RemyLebeau i have tried the code in [this post](https://stackoverflow.com/questions/49025941/how-to-create-process-as-user-with-arguments) but still no luck. My app is on [GitHub](https://github.com/RallyTuning/InitianPositionApp) there are 2 branches with different methods. But both cause fullscreen application to blink and lost focus (such as games in full screen or YouTube/streaming apps in full screen). Anders, yes tried this too but after hours wasted on get the app handle, i discovered that in this way the GUI of the nested exe sometimes is not draw correctly. Forcing me restart twince – Tyler Sep 13 '22 at 19:26
0

Solved by myself in this way:

        Funzioni.HWnd = IntPtr.Zero;

        // Start hidden the process
        PSI = new ProcessStartInfo(Funzioni.AppPath)
        {
            CreateNoWindow = true,
            RedirectStandardInput = false,
            RedirectStandardOutput = false,
            RedirectStandardError = false,
            WindowStyle = ProcessWindowStyle.Hidden
        };

        P = Process.Start(PSI);

        int MaxCount = 10000;
        int Count = 0;
        Thread.Sleep(500);
        while (Funzioni.HWnd == IntPtr.Zero || Count > MaxCount)
        {
            P.WaitForInputIdle();
            P.Refresh();
            // Get the hidden main handle
            Funzioni.HWnd = Funzioni.EnumerateProcessWindowHandles(P.Id).First();
            Count++;
        }

        if (Funzioni.HWnd == IntPtr.Zero) throw new ApplicationException("The process is taking long to start");

        // Set the parent exe
        Funzioni.SetParent(Funzioni.HWnd, Pnl_Centrale.Handle);

        // Set the window of the nested exe in no-top most and not active
        Funzioni.SetWindowPos(Funzioni.HWnd, (IntPtr)SpecialWindowHandles.HWND_NOTOPMOST,
            Funzioni.ExePosX, Funzioni.ExePosY, Funzioni.ExeLarghezza, Funzioni.ExeAltezza - Funzioni.AltezzaToolBar,
         (uint)SetWindowPosFlags.SWP_NOACTIVATE | (uint)SetWindowPosFlags.SWP_NOOWNERZORDER);

        // Move again the the window in the desired position (i don't know why the function above don't work if using "NOTOPMOST"
        Funzioni.MoveWindow(Funzioni.HWnd, Funzioni.ExePosX, Funzioni.ExePosY, Funzioni.ExeLarghezza, Funzioni.ExeAltezza - Funzioni.AltezzaToolBar, true);
        P.Refresh();
        
        // Show the back the hidden process/ese/window
        Funzioni.ShowWindow(Funzioni.HWnd, 1);

WinAPI:

    #region WinApi

    [DllImport("user32.dll", SetLastError = true)]
    internal static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

    [DllImport("user32.dll", SetLastError = true)]
    internal static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);

    [DllImport("user32.dll", SetLastError = true)]
    internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    internal delegate bool EnumThreadDelegate(IntPtr hWnd, IntPtr lParam);

    [DllImport("user32.dll")]
    internal static extern bool EnumThreadWindows(int dwThreadId, EnumThreadDelegate lpfn,
        IntPtr lParam);

    internal static IEnumerable<IntPtr> EnumerateProcessWindowHandles(int processId)
    {
        var handles = new List<IntPtr>();

        foreach (ProcessThread thread in Process.GetProcessById(processId).Threads)
            EnumThreadWindows(thread.Id,
                (hWnd, lParam) => { handles.Add(hWnd); return true; }, IntPtr.Zero);

        return handles;
    }

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool InvalidateRect(IntPtr hWnd, IntPtr rect, bool bErase);

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

    [DllImport("user32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, UInt32 uFlags);

    #endregion

Enums:

    public enum SpecialWindowHandles
    {
        // ReSharper disable InconsistentNaming
        /// <summary>
        ///     Places the window at the top of the Z order.
        /// </summary>
        HWND_TOP = 0,
        /// <summary>
        ///     Places the window at the bottom of the Z order. If the hWnd parameter identifies a topmost window, the window loses its topmost status and is placed at the bottom of all other windows.
        /// </summary>
        HWND_BOTTOM = 1,
        /// <summary>
        ///     Places the window above all non-topmost windows. The window maintains its topmost position even when it is deactivated.
        /// </summary>
        HWND_TOPMOST = -1,
        /// <summary>
        ///     Places the window above all non-topmost windows (that is, behind all topmost windows). This flag has no effect if the window is already a non-topmost window.
        /// </summary>
        HWND_NOTOPMOST = -2
        // ReSharper restore InconsistentNaming
    }

    [Flags]
    public enum SetWindowPosFlags : uint
    {
        // ReSharper disable InconsistentNaming

        /// <summary>
        ///     If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
        /// </summary>
        SWP_ASYNCWINDOWPOS = 0x4000,

        /// <summary>
        ///     Prevents generation of the WM_SYNCPAINT message.
        /// </summary>
        SWP_DEFERERASE = 0x2000,

        /// <summary>
        ///     Draws a frame (defined in the window's class description) around the window.
        /// </summary>
        SWP_DRAWFRAME = 0x0020,

        /// <summary>
        ///     Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
        /// </summary>
        SWP_FRAMECHANGED = 0x0020,

        /// <summary>
        ///     Hides the window.
        /// </summary>
        SWP_HIDEWINDOW = 0x0080,

        /// <summary>
        ///     Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
        /// </summary>
        SWP_NOACTIVATE = 0x0010,

        /// <summary>
        ///     Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
        /// </summary>
        SWP_NOCOPYBITS = 0x0100,

        /// <summary>
        ///     Retains the current position (ignores X and Y parameters).
        /// </summary>
        SWP_NOMOVE = 0x0002,

        /// <summary>
        ///     Does not change the owner window's position in the Z order.
        /// </summary>
        SWP_NOOWNERZORDER = 0x0200,

        /// <summary>
        ///     Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
        /// </summary>
        SWP_NOREDRAW = 0x0008,

        /// <summary>
        ///     Same as the SWP_NOOWNERZORDER flag.
        /// </summary>
        SWP_NOREPOSITION = 0x0200,

        /// <summary>
        ///     Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
        /// </summary>
        SWP_NOSENDCHANGING = 0x0400,

        /// <summary>
        ///     Retains the current size (ignores the cx and cy parameters).
        /// </summary>
        SWP_NOSIZE = 0x0001,

        /// <summary>
        ///     Retains the current Z order (ignores the hWndInsertAfter parameter).
        /// </summary>
        SWP_NOZORDER = 0x0004,

        /// <summary>
        ///     Displays the window.
        /// </summary>
        SWP_SHOWWINDOW = 0x0040,

        // ReSharper restore InconsistentNaming
    }

Unfortunately, sometimes (not ever) the GUI of the nested app is not draw correctly, forcing me to restart it manually after the auto-restart every 60 mins. I have used [DllImport("user32.dll")] static extern bool UpdateWindow(IntPtr hWnd); but without luck. Any other redraw/function are not working. There is a way to force redraw before show up?

Also, the code above, make the Windows status bar to pop up while are in full screen on (for example) YouTube. Any suggestions to avoid this too?

Tyler
  • 416
  • 4
  • 11