Home > Software engineering >  Start an external process inside a panel without other apps losing focus
Start an external process inside a panel without other apps losing focus

Time:09-16

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

CodePudding user response:

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.

CodePudding user response:

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?

  • Related