March, 2011

  • The Old New Thing

    2011 Q1 link clearance: Microsoft blogger edition

    • 11 Comments

    It's that time again: Linking to other Microsoft bloggers.

  • The Old New Thing

    Having an owner window from another process is tricky, but it's sometimes the right thing to do

    • 6 Comments

    A customer had a main program (let's call it A) and a helper program (let's call it B), and the customer wanted and wanted B to act like a modal dialog relative to A.

    When B is launched, we disable A's window and then call SetForegroundWindow(hwndB) to simulate a modal dialog. How do we make sure that focus goes to B's window and not A's? We've found that if the user clicks on the (now-disabled) window from the process A, then window B loses focus. This is not the behavior from regular modal windows however: For normal modal windows, clicking on the disabled owner activates the modal popup.

    One idea is to watch for WM_ACTIVATE(FALSE) notifications on hwndSecondProcess, and if the window that took focus from us is the one from the first process, then take it back with SetForegroundWindow(hwndSecondProcess).

    But then we wondered, since we disabled window A, will it even get the normal activation message?

    Since the window is disabled, it will not receive activation messages because disabled windows cannot be activated. So no, this solution won't work.

    The subject line of the question, however, gave the answer without even realizing it. The subject was Out-of-proc pseudo-parent/child window relationship. (Well, okay, the subject line confused parent/child with owner/owned, but that's a common source of sloppiness when talking about the relationship among windows.)

    Instead of having a pseudo-owner/owned window relationship, just have a real one. Why fake it when you can get the real thing?

    When you call DialogBox in process B, pass hwndA as the owner window. Now the two windows have a genuine owner/owned relationship, along with the standard behaviors that come with it. It's legal to have an owner/owned relationship that crosses process boundaries. Note that when you do this, it attaches the two threads' input queues so you have to be careful if both windows process input at the same time. Fortunately, in the modal dialog case, only one of the windows accepts input at a time, so the scariest part of attached input queues doesn't apply.

  • The Old New Thing

    How do I get the title of a dialog from a dialog resource?

    • 13 Comments

    A customer submitted the following question:

    We are developing automated tests for our application. Among other things, our application uses property sheets, which means that the name of the tab is stored as the title of the dialog template resource. Since we want our automated tests to run on all language versions of our application, we don't want to hard-code the tab names in our automated test. I have not been able to find any information on how to programmatically extract the dialog titles from the dialog resources. Any pointers would be appreciated.

    I replied with some pointers:

    The customer was grateful for the pointers, then asked:

    Then the only way to do this is to load the dialog resource and parse the data looking for the string I want? Is it even possible to do this in C#?

    Well it depends on what your definition of "the only way" is.

    At the end of the day, somebody has to load the dialog resource and parse it, because after all that is what you said you want to do: "I want to get the title of the dialog from the dialog resource." The alternative is, what, psychic powers?

    There is no dialog template parsing library that comes with Win32. If you don't want to do the parsing, then maybe you can find somebody else who will. And if you're lucky, that other person may even have provided a C# interface.

  • The Old New Thing

    Although the default icon for a shortcut is the icon of the target, you can override that

    • 17 Comments

    A customer reported that a shortcut they deployed to their employees' desktops was triggering unwanted server traffic.

    My customer deploys a shortcut on %ALLUSERSPROFILE%\Desktop, and this shortcut points to an EXE file on a remote server. Once a local user logs on, the computer will try logging onto the remote computer to query information and generate a login failure alert on the server.

    Is there any way to stop Explorer from querying the shortcut information?

    Fortunately, the customer provided context for the question, because the question the customer is asking doesn't actually match the scenario. The customer doesn't want to stop Explorer from querying the shortcut information; the customer just wants to stop Explorer from contacting the server to get the icon.

    The default icon for a shortcut is the icon of the target, and in order to get that icon, Explorer needs to contact the target. But you can override that default. Programmatically, you call IShellLink::SetIconLocation; interactively, you view the shortcut's properties and click Change Icon.... In either case, set it to an icon that doesn't reside on the server. Save the changes and deploy the modified shortcut.

  • The Old New Thing

    Why did Win32 define BOOL as a signed int instead of an unsigned int?

    • 48 Comments

    Igor Levicki wants somebody from Microsoft to explain why BOOL was defined as a signed int instead of an unsigned int.

    You don't need to work for Microsoft to figure this out. All the information you need is publically available.

    Quoting from K&R Classic, which was the operative C standards document at the time Windows was being developed:

    7.6 Relational Operators

    The [relational operators] all yield 0 if the specified relation is false and 1 if it is true. The type of the result is int.

    Win32 defined BOOL as synonymous with int because Brian and Dennis said so. If you want to know why Brian and Dennis decided to have the result of relational operators be signed instead of unsigned, you'll have to ask them.

  • The Old New Thing

    Paul Cézanne and Camille Saint-Saëns may have similar-sounding last names, but they are not the same person

    • 12 Comments

    Next week, the Seattle Symphony Orchestra performs the Saint-Saëns Organ Symphony, but the people responsible for the symphony's radio advertisements don't realize that.

    As the strains of the symphony resound in the background, the announcer proudly announces that tickets are still available for "Cézanne's Organ Symphony."

    The names Cézanne and Saint-Saëns may sound similar, but I can assure you that they are not the same person. Here's a handy chart:

    Cézanne Saint-Saëns
    French X X
    Born in 1830's X X
    Master painter X  
    Master composer   X
    Carnival X  
    The Carnival of the Animals   X
    Died of pneumonia X X

    This is not the first time the Seattle Symphony's radio announcer has made this substitution. I don't know whether somebody is giving him incorrect copy to read, or whether he is performing on-the-fly auto-correction. Or maybe the announcer guy asked, "How do you pronounce Saint-Saëns?" and somebody answered, "It sounds like Cézanne."

    And now that I cleared everything up, let me confuse things some more:

  • The Old New Thing

    How do I monitor, or even control, the lifetime of an Explorer window?

    • 19 Comments

    A customer wanted help with monitoring the lifetime of an Explorer window.

    We want to launch a copy of Explorer to open a specific folder, then wait until the user closes the folder before continuing. We tried launching a copy of Explorer with the folder on the command line, then doing a Wait­For­Single­Object on the process handle, but the wait sometimes completes immediately without waiting. How do we wait until the user closes the Explorer window?

    This is another case of solving a problem halfway and then having trouble with the other half.

    The reason that Wait­For­Single­Object returns immediately is that Explorer is a single-instance program (well, limited-instance). When you open an Explorer window, the request is handed off to a running copy of Explorer, and the copy of Explorer you launched exits. That's why your Wait­For­Single­Object returns immediately.

    Fortunately, the customer was willing to explain their underlying problem.

    We have a wizard that creates some files in a directory based on information provided by the user, and we want to launch Explorer to view that directory so users can verify that things are set up the way they want them. When users close the Explorer window, we ask them if everything was good; if not, then we back up and let the user try again.

    Aha, the program is using Explorer as a "view this folder for a little while" subroutine. Unfortunately, Explorer doesn't work that way. For example, the user might decide to use the Address Bar and go visit some other folders completely unrelated to your program, and your program would just be sitting there waiting for the user to close that window; meanwhile, the user doesn't realize that your program is waiting for it.

    What you can do is host the Explorer Browser control inside a page of your wizard and control it with interfaces like IExplorer­Browser. You can disable navigation in the Explorer Browser (so the user can look only at the folder you want to preview), and the user can click Back if they want to try again or Next if they are happy and want to continue. This has the additional advantage of keeping all the parts of your wizard inside the wizard framework itself, allowing users to continue using the wizard navigation model that they are already familiar with.

    A sample program which uses the Explorer Browser control can be found in the Platform SDK.

    For the impatient, here's the scratch program version. Note that this is the minimal version; in real life, you would probably want to set some options and stuff like that.

    #include <shlobj.h>
    
    IExplorerBrowser *g_peb;
    
    void
    OnSize(HWND hwnd, UINT state, int cx, int cy)
    {
        if (g_peb) {
            RECT rc = { 0, 0, cx, cy };
            g_peb->SetRect(NULL, rc);
        }
    }
    
    BOOL
    OnCreate(HWND hwnd, LPCREATESTRUCT lpcs)
    {
        BOOL fSuccess = FALSE;
        RECT rc;
        PIDLIST_ABSOLUTE pidl = NULL;
        if (SUCCEEDED(CoCreateInstance(CLSID_ExplorerBrowser, NULL,
                             CLSCTX_INPROC, IID_PPV_ARGS(&g_peb))) &&
            GetClientRect(hwnd, &rc) &&
            SUCCEEDED(g_peb->Initialize(hwnd, &rc, NULL)) &&
            SUCCEEDED(SHParseDisplayName(
                             L"C:\\Program Files\\Internet Explorer",
                                            NULL, &pidl, 0, NULL)) &&
            SUCCEEDED(g_peb->SetOptions(EBO_NAVIGATEONCE)) &&
            SUCCEEDED(g_peb->BrowseToIDList(pidl, SBSP_ABSOLUTE))) {
            fSuccess = TRUE;
        }
        ILFree(pidl);
        return fSuccess;
    }
    
    void
    OnDestroy(HWND hwnd)
    {
        if (g_peb) {
            g_peb->Destroy();
            g_peb->Release();
        }
        PostQuitMessage(0);
    }
    

    This same technique of hosting the Explorer Browser control can be used for other types of "build your own burrito" scenarios: For example, you might host the Explorer Browser control in a window and tell users to copy files into that window. When they click OK or Next or whatever, you can enumerate the contents of the folder and do your business.

    Armed with this knowledge, you can answer these customers' questions:

    We have found that the process state of Explorer.exe changes to signaled before the process terminates. Here's a sample program:

    int _tmain(int argc, TCHAR **argv)
    {
     STARTUPINFO si = { sizeof(si) };
     PROCESS_INFORMATION pi;
     if (CreateProcess(TEXT("C:\\Windows\\Explorer.exe"), TEXT(" /e,C:\\usr"),
                       NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
      WaitForSingleObject(pi.hProcess);
      CloseHandle(pi.hProcess);
      CloseHandle(pi.hThread);
     }
     return 0;
    }
    

    If we change "Explorer.exe" to "Notepad.exe" then the process handle is signaled after Notepad terminates, as expected.

    We have a 32-bit shell extension for which a 64-bit version is not available. Since our clients are running 64-bit Windows, the 32-bit shell extension is not available in Explorer. How can we obtain access to this context menu?
    We have a shell extension that is not UAC-compliant. It requires that the user have administrative privileges in order to function properly. We would rather not disable UAC across the board just for this one shell extension. Is there a workaround that lets us run Explorer elevated temporarily?

    Bonus sample program: The Explorer Browser Search Sample shows how to filter the view.

    Bonus alternative: If you really just want to watch Explorer windows rather than host one, you can use the ShellWindows object, something I covered many years ago (and followed up with a much shorter scripting version).

  • The Old New Thing

    How can I generate a consistent but unique value that can coexist with GUIDs?

    • 18 Comments

    A customer needed to generate a GUID for each instance of a hardware device they encounter:

    The serial number for each device is 20 bits long (four and a half bytes). We need to generate a GUID based on each device, subject to the constraints that when a device is reinserted, we generate the same GUID for it, that no two devices generate the same GUID, and that the GUIDs we generate not collide with GUIDs generated by other means. One of our engineers suggested just running uuidgen and substituting the serial number for the final nine hex digits. Is this a viable technique?

    This is similar to the trap of thinking that half of a GUID is just as unique as the whole thing. Remember that all the pieces of a GUID work together to establish uniqueness. If you just take parts of it, then the algorithm breaks down.

    For this particular case, you're in luck. The classic Type 1 GUID uses 60 bits to encode the timestamp and 48 bits to identify the location (computer). You can take a network card, extract the MAC address, then smash the card with a hammer. Now you have a unique location. Put your twenty bits of unique data as the timestamp, and you have a Type 1 GUID that is guaranteed never to collide with another GUID.

    If you have more than 60 bits of unique data, then this trick won't work. Fortunately, RFC4122 explains how to create a so-called name-based UUID, which is a UUID that can be reliably regenerated from the same source data. Section 4.3 explains how it's done. The result is either a type 3 or type 5 UUID, depending on which variant of the algorithm you chose.

  • The Old New Thing

    Function requirements are cumulative: If you fail to meet any of them, then all bets are off

    • 33 Comments

    A customer was having problems with the Wait­For­Multiple­Objects function:

    We are looking for a clarification of the behavior of Wait­For­Multiple­Objects. We have a thread that waits on two handles (call them Handle1 and Handle2) with Wait­For­Multiple­Objects, bWaitAll = FALSE. Under certain conditions, we signal Handle1 and close Handle2 from another thread while the wait is in progress. This results in WAIT_FAILED being returned from the wait call. MSDN is not clear on what the expected behavior is here. On the one hand, it says

    1. When bWait is FALSE, this function checks the handles in the array in order starting with index 0, until one of the objects is signaled. If multiple objects become signaled, the function returns the index of the first handle in the array whose object was signaled.

    This description implies that the wait should never fail, because the function should have noticed that Handle1 is signaled before it got around to noticing that Handle2 was invalid.

    On the other hand, the documentation also says

    1. If one of these handle is closed while the wait is still pending, the function's behavior is undefined.

    What behavior is guaranteed here?

    Once you violate a constraint (in this case, the constraint that the handles remain valid for the duration of the wait operation), you have failed to meet the prerequisites and the behavior is undefined. You can't say, "Well, sure you say I can't do X, but if you follow exactly the steps given in this description of how signaled objects are selected, then the function wouldn't even have noticed X before coming to a decision, so the fact that I broke one of the rules is irrelevant!"

    The description of the behavior of the Wait­For­Multiple­Objects function when bWait is FALSE is not an implementation specification. It's a description of how to interpret the behavior of the function. The algorithmic way the function behavior is described is to assist in understanding the behavior; it doesn't mean that the function actually follows the algorithm step-by-step. (In reality, there is no polling loop, as the algorithmic description implies. All the handles are waited on simultaneously. It's like Lebesgue integration: You integrate over the entire domain at once.)

    An algorithm-free description of the behavior when bWait is false might go like this:

    1. When bWait is FALSE, the function does not return until one of the handles in the array becomes signaled. The return value is the smallest index corresponding to a signaled handle.

    This description is purely declarative but gives you no mental model.

    It's like saying that "Water seeks its own level." Water doesn't have a will that compels it to behave in a certain way, but describing the behavior in that way makes reasoning about water easier.

  • The Old New Thing

    Why is there the message '!Do not use this registry key' in the registry?

    • 40 Comments

    Under Software\Microsoft\Windows\Current­Version\Explorer\Shell Folders, there is a message to registry snoopers: The first value is called "!Do not use this registry key" and the associated data is the message "Use the SH­Get­Folder­Path or SH­Get­Known­Folder­Path function instead."

    I added that message.

    The long and sad story of the Shell Folders key explains that the registry key exists only to retain backward compatibility with four programs written in 1994. There's also a TechNet version of the article which is just as sad but not as long.

    One customer saw this message and complained, "That registry key and that TechNet article explain how to obtain the current locations of those special folders, but they don't explain how to change them. This type of woefully inadequate documentation only makes the problem worse."

    Hey, wow, a little message in a registry key and a magazine article are now "documentation"! The TechNet article is historical background. And the registry key is just a gentle nudge. Neither is documentation. It's not like I'm going to put a complete copy of the documentation into a registry key. Documentation lives in places like MSDN.

    But it seems that some people need more than a nudge; they need a shove. Let's see, we're told that the functions for obtaining the locations of known folders are SH­Get­Folder­Path and its more modern counterpart SH­Get­Known­Folder­Path. I wonder what the names of the functions for modifying those locations might be?

    Man that's a tough one. I'll let you puzzle that out for a while.

    Okay, here, I'll tell you: The corresponding functions go by the completely unobvious names SH­Set­Folder­Path and SH­Set­Known­Folder­Path.

    Sorry you had to use your brain. I'll let you get back to programming now.

Page 1 of 3 (28 items) 123