Today's snippet comes from an issue that Brian discovered in the production code of a large telecomunication company's call center software. It attempts to solve a fairly simple problem: get the handle to a specified window and, if it can't be found, try again for MAX_SECONDS. However, there was a bit of an issue with the default wait time...

 

// Retrieve the window.
public static IntPtr GetWindow(string className, string title)
{
    // 86400 is the number of seconds in a day
    return GetWindow(className, title, 86400, IntPtr.Zero); 
}

// Retrieve the window (with wait and avoid)
public static IntPtr GetWindow(string className, string title, 
                               int maxWaitInSeconds, IntPtr avoidWindow)
{
    IntPtr window = IntPtr.Zero;
    int max = 86400 * 4;
    int i = 0;

    // 86400 is the number of seconds in a day
    if (maxWaitInSeconds < 86400) 
    {
        max = maxWaitInSeconds * 4;
    }

    window = Win32API.FindWindow(className, title);

    while ( ((window == IntPtr.Zero) 
              || (window != IntPtr.Zero && window == avoidWindow)) 
           && (i++ < max))
    {
        Thread.Sleep(250);
        window = Win32API.FindWindow(className, title);
    }    
    return window;
}

Being a call center application, they had a hard time asking the operator to hold until the application finishes waiting twenty-four hours for the process to finish...

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!