C# - Process: wait until MainWindow was created

By , 7/28/2015
(0 ratings)
When you start a program to interact later with its GUI you should check whether the main window is already created.
This extension method simplifies the procedure a little bit.
namespace System.Diagnostics
{
    using System.Threading;

    public static class Process_Extensions
    {
        /// <summary>
        /// Waits until the MainWindow of an process was created.
        /// </summary>
        /// <param name="process">The process that was startet.</param>
        /// <returns><c>true</c> if the process runs and has a MainWindow; otherwise <c>false</c></returns>
        public static bool WaitForMainWindow(this Process process)
        {
            while (!process.HasExited && process.MainWindowHandle == IntPtr.Zero)
                Thread.Sleep(10);
            return !process.HasExited;
        }

        /// <summary>
        /// Waits until the MainWindow of an process was created.
        /// </summary>
        /// <param name="process">The process that was startet.</param>
        /// <param name="timeout">The maximum of time to wait until the method returns.</param>
        /// <returns><c>true</c> if the process runs and has a MainWindow; otherwise <c>false</c></returns>
        public static bool WaitForMainWindow(this Process process, uint timeout)
        {
            var start = DateTime.Now;
            while (!process.HasExited && process.MainWindowHandle == IntPtr.Zero)
            {
                Thread.Sleep(10);
                if ((DateTime.Now - start).TotalMilliseconds >= timeout)
                {
                    return false;
                }
            }
            return !process.HasExited;
        }
    }
}

Comments

 

Log in, to comment!