April, 2010

  • The Old New Thing

    How to edit the security attributes of more than one file at a time


    In Windows XP, you could select multiple files, right-click them, then select Properties. The resulting property sheet includes a Security page which lets you edit the security attributes of those files. But when you repeat this exercise on Windows Vista or Windows 7, the Security page is missing. Why doesn't Explorer let you edit the security attributes of more than one file at a time?

    Windows might need to display an elevation prompt if any of the files in the collection require administrator privileges in order to modify the security attributes. The security prompt needs to tell you why you are elevating, but if you selected twenty files, there isn't room to display all twenty of them in the elevation dialog. Truncating the results means that users may be tricked into changing the security of files they didn't intend. "Grant everyone full access to X, Y, Z, and 17 other files?" How do you know your multiselect didn't accidentally include MergerPlans.doc? (Maybe there's some malware that waits for people to change security on multiple items and quietly sneaks NTOSKRNL.EXE into the file list.) Alexander Grigoriev says, "Holding forever to dangerous features is BAD BAD BAD."

    If you need to modify the security attributes on a whole bunch of files, you can use the CACLS program, one of the command line tools that messes with security descriptors. If you want to modify the attributes of all the files in a directory tree, you can edit the security attributes of the root of the tree and indicate that you want to propagate inheritable attributes.

    Pre-emptive hate: "I hate Microsoft for removing this feature." (Okay, that was too tame. A PROPER HATE REQUIRES SENTENCES IN ALL-CAPS.) And you wonder why I don't do Tips/Support topics often. Whenever I provide a tip that lets you work around something, everybody rants about the problem the workaround exists to address.

  • The Old New Thing

    Email tip: When you say that something didn't work, you have to say how it didn't work


    I illustrate this point with an imaginary conversation, inspired by actual ones I've seen (and, occasionally, been a frustrated party to).

    From: X

    I want to do ABC, but I don't have a DEF. Anybody know of a workaround?

    Somebody has an idea:

    From: Y

    Try mounting this ISO file into a virtual machine and trying the ABC from there.

    Unfortunately, it didn't work:

    From: X

    I tried that, but it didn't work. Any other ideas?

    When somebody suggests a troubleshooting step or a workaround, but when you try it and it doesn't work, you need to say how it didn't work. The person who made the suggestion had some expectation that it would work, and just saying that it didn't work will probably just generate an unhelpful response like "Well, try again." Which doesn't help anybody.

    In this example (which I just made up), a better response from X would be something like this:

    • "I tried that, but it didn't work. Virtual PC refused to load the ISO image, putting up the error message 'The CD image could not be captured. You may not have the proper access privileges to the CD image files.'"
    • "I tried that, but it didn't work. Virtual PC loaded the ISO image, but when I tried to view the contents of the CD, I got 'Not ready reading drive D.'"
    • "I tried that, but it didn't work. Virtual PC loaded the ISO image, but when I double-clicked the ABC file, I got the same error that I got when I tried to do ABC directly."

    Each of these is a different failure mode that suggests a different course of action.

    And then the response probably won't be, "Well, try again."

  • The Old New Thing

    It's a miracle humanity has survived this far, if reaction to the inability to make or receive a telephone call is to be believed


    In one of the mailing lists devoted to chatting among people who work in a particular cluster of Microsoft office buildings, there was some discussion of the quality of mobile phone coverage in the parking garage.

    "I can't get a signal in any of the underground levels. This is intolerable!"

    Here's an idea: Walk to ground level and make your call there.

    "But what if it's an emergency?"

    Then run.

    (Or use one of the emergency phones.)

    Sometimes I wonder how humanity had managed to survive prior to the installation of mobile phone cell towers. Had these people been born just 30 years earlier, they wouldn't have been able to get through everyday life, having never developed their ability to plan anything in advance.

    I remember the days when it was common for people not to be reachable for (gasp) hours at a time. You couldn't even leave a message at the beep; you just had to try again later. It apparently is a miracle that our species didn't go extinct.

  • The Old New Thing

    How do I switch a window between normal and fullscreen?


    Frederic Delhoume wants to know if there is a simple example of code that switches an application from windowed to fullscreen. He then included a code fragment that did some crazy things with parent windows and hiding and showing.

    You're making it way, way harder than it needs to be. Let's start with our scratch program and make these changes:

    WINDOWPLACEMENT g_wpPrev = { sizeof(g_wpPrev) };
    void OnLButtonUp(HWND hwnd, int x, int y, UINT keyFlags)
      DWORD dwStyle = GetWindowLong(hwnd, GWL_STYLE);
      if (dwStyle & WS_OVERLAPPEDWINDOW) {
        MONITORINFO mi = { sizeof(mi) };
        if (GetWindowPlacement(hwnd, &g_wpPrev) &&
                           MONITOR_DEFAULTTOPRIMARY), &mi)) {
          SetWindowLong(hwnd, GWL_STYLE,
                        dwStyle & ~WS_OVERLAPPEDWINDOW);
          SetWindowPos(hwnd, HWND_TOP,
                       mi.rcMonitor.left, mi.rcMonitor.top,
                       mi.rcMonitor.right - mi.rcMonitor.left,
                       mi.rcMonitor.bottom - mi.rcMonitor.top,
      } else {
        SetWindowLong(hwnd, GWL_STYLE,
                      dwStyle | WS_OVERLAPPEDWINDOW);
        SetWindowPlacement(hwnd, &g_wpPrev);
        SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
                     SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
    // add to WndProc
        HANDLE_MSG(hwnd, WM_LBUTTONUP, OnLButtonUp);

    To avoid getting into the intricacies of hotkeys and accelerators, I opted to toggle to fullscreen on a click. When the button goes up, we check whether we are currently in normal mode or fullscreen mode by sniffing at our window styles. If we are in normal mode, we save the current window placement and get the dimensions of the current monitor. And then the magic happens: We remove the caption and other decorations from our window style and reposition the window so it covers the entire monitor. An important flag to pass here is SWP_FRAME­CHANGED, which tells the window manager to recalculate the window decorations (which we need it to do because we just changed them).

    When returning from fullscreen, we just undo what we had done when we went fullscreen: We restore the caption and other decorations to our window and restore the original window state.

    And that's all there is to it. You don't have to do anything special to get the taskbar to "get out of the way"; the taskbar recognizes when applications have gone fullscreen and automatically gets out of the way.

  • The Old New Thing

    The difference between your job and your hobby


    There was an internal discussion about what Microsoft employees should be doing that do not directly relate to their job responsibilities, such as what text editor programmers should be using to write and edit code. Should anybody who uses a programming editor other than Visual Studio be branded a traitor? How about somebody who prefers a smartphone made by a certain Cupertino company? (And for some reason, this discussion took place on the Microsoft bloggers mailing list, because many people consider it a mailing list whose members are bloggers, as opposed to a mailing list for discussing blogging. I happen to adhere to the second definition.)

    These sorts of discussions generate far more heat than light, and I felt compelled to chime in:

    If it doesn't result in a bigger number in my bank account, then it's a hobby. It's noble that many people have Microsoft-focused hobbies. My hobbies are knitting and modern Germanic languages.
  • The Old New Thing

    Why does the wireless connection dialog ask for your password twice?


    Martin wonders why the wireless networking dialog asks you to type your password twice when connecting to an existing network.

    Yeah, that bothers me too, and I don't know why either.

    But while we're on the topic of wireless networking, I thought I'd share a little program that is just as useless as my answer above. (If other people get to hijack the topic, then I want to also.)

    Back in the early days of Windows XP, I found that my wireless networking adapter would constantly disconnect and reconnect. I never figured out why, but I did have a theory. (Theory: The wireless zero configuration service saw another access point and said, "Hey, that access point over there looks much nicer than then one I'm currently connected to. I'm going to drop my current connection and see if maybe that other access point will go out with me." And then it went up to that other access point and asked it out on a date. When the other access point said no, it came crawling back to the original access point. Repeat.)

    Anyway, to avoid this problem (which went away after a while for reasons unclear; maybe it was fixed, maybe whatever situation triggered the problem went away, I didn't bother investigating), I wrote a program which did two very simple things:

    1. If the wireless networking adapter was connected to an access point, then turn off the wireless zero configuration service.
    2. If the wireless networking adapter was not connected to an access point, then turn on the wireless zero configuration service.

    In other words, it automates the process described on this Web page. (I like how that article was copied in its entirety to another site, which replaced the author's name. Now that's chutzpah.)

    Mind you, the program really is no longer interesting in and of itself any more because the underlying problem went away, but I thought it could serve as an illustration of how you can put together some simple things to make a useful tool.

    First, I changed the security descriptor on the wireless zero configuration service so that my account had permission to turn it on and off.

    Second, I added this code to a program that hangs out my Startup group which monitors various things I like to monitor. (I have one program that monitors several things just to cut down on the number of processes hanging around on my machine.) The code has been compressed and reformatted to get rid of the uninteresting parts.

    class MonitorWireless
        : m_hWait(NULL)
          ZeroMemory(&m_o, sizeof(m_o));
        if (m_hWait) UnregisterWaitEx(m_hWait, INVALID_HANDLE_VALUE);
        if (m_o.hEvent) CloseHandle(m_o.hEvent);
      BOOL Initialize();
      static void CALLBACK s_OnChange(PVOID lpParameter, BOOLEAN)
        MonitorWireless *self =
        self->CheckIPAddress(); // something changed - check it again
      void CheckIPAddress();
      static void StartStopService(BOOL fStart);
        HANDLE m_hWait;
        OVERLAPPED m_o;

    The class definition is all very boring. Our class has an OVERLAPPED structure which we use to register for IP address change notifications, and it has a handle to a registered wait, which takes advantage of the thread pool to reduce the number of threads used by the process.

    BOOL MonitorWireless::Initialize()
      m_o.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
      if (!m_o.hEvent) return FALSE;
      if (!RegisterWaitForSingleObject(&m_hWait, m_o.hEvent,
                          s_OnChange, this, INFINITE, 0)) return FALSE;
      return TRUE;

    When the object is initialized, it creates the handle that we will ask to be set whenever the computer's IP address changes, and then registers a wait on that handle with a callback function. When the event is signaled, we check the IP address. And to start the ball rolling, we check the IP address at initialization.

    void MonitorWireless::CheckIPAddress()
      ULONG ulSize = 0;
      if (GetIpAddrTable(NULL, &ulSize, 0) ==
                                         ERROR_INSUFFICIENT_BUFFER) {
        PMIB_IPADDRTABLE piat = reinterpret_cast<PMIB_IPADDRTABLE>
                                    (LocalAlloc(LMEM_FIXED, ulSize));
        if (piat) {
          if (GetIpAddrTable(piat, &ulSize, 0) == ERROR_SUCCESS) {
            BOOL fFound = FALSE;
            for (DWORD dwIndex = 0; dwIndex < piat->dwNumEntries;
                 dwIndex++) {
              PMIB_IPADDRROW prow = &piat->table[dwIndex];
              if (prow->dwAddr == 0) continue;
              if ((prow->wType & (MIB_IPADDR_DYNAMIC |
                                  MIB_IPADDR_DELETED |
                                  MIB_IPADDR_DISCONNECTED)) !=
                                  MIB_IPADDR_DYNAMIC) continue;
              fFound = TRUE;
      HANDLE h;
      NotifyAddrChange(&h, &m_o);

    We start by getting the IP address table (doing the standard two-step of first asking how much memory we need to hold it, allocating the memory, and then filling the buffer) and walking through each IP address. If we find an entry with an IP address that is dynamic, not deleted, and not disconnected, then we declare ourselves happy; otherwise we are sad. If we are happy, then we stop the wireless zero configuration service; if we are sad, then we start it.

    void MonitorWireless::StartStopService(BOOL fStart)
      SC_HANDLE sc;
      sc = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT |
      if (sc) {
        SC_HANDLE scWzcsvc = OpenService(sc, TEXT("wzcsvc"),
                       fStart ? SERVICE_START 
                              : SERVICE_STOP | SERVICE_QUERY_STATUS);
        if (scWzcsvc) {
          if (fStart) StartService(scWzcsvc, 0, NULL);
          else        StopService(scWzcsvc);

    To start or stop the service, we first connect to the service control manager, open the service we want to start/stop, and then, well, start or stop it.

    There is already a Start­Service function, but no Stop­Service function, so I wrote my own:

    void StopService(SC_HANDLE sc)
     if (QueryServiceStatus(sc, &ss) &&
         ss.dwCurrentState != SERVICE_STOPPED &&
         ss.dwCurrentState != SERVICE_STOP_PENDING)
       ControlService(sc, SERVICE_CONTROL_STOP, &ss);

    If the service is not already stopped (or stopping), then we tell it to stop.

    And there you have it, a program that you don't need any more. But the point here was more to show how you can put together some basic elements to solve a simple problem.

    Techniques illustrated:

    • Registering a wait in the thread pool.
    • Registering asynchronously for IP address changes.
    • Starting and stopping a service.
  • The Old New Thing

    Our legal department suggests you skip our salad dressing and just eat an avocado


    I saw a bottle of salad dressing with very strange fine print. The picture on the bottle is of half an avocado. But the fine print on the bottle reads "Does not contain avocados."

    Okay, so the picture on the bottle isn't a picture of the product. This is strange but not entirely unheard of. After all, a box of Girl Scout cookies has pictures of Girl Scouts, not cookies.

    The thing that struck me was the second half of the fine print. It reads "Serving suggestion."


    Apparently, the suggested way of enjoying their salad dressing is to eat half an avocado with no salad dressing on it.

    Pre-emptive snarky comment: "PCs should have come with a suggestion to use the computer without Windows Vista on it."

  • The Old New Thing

    He bought the whole seat, but we only needed the edge


    After the Windows 95 project was released to manufacturing, but before the launch event itself, the team finally had a chance to relax and unwind after many years of hard work. The project manager decided to have a morale event to get everyone together to do something fun. A typical morale event might be going to see a baseball game, renting out a movie theater to watch the latest action flick, or something as simple as a picnic or a softball game.

    But this time, the project manager decided to do something different, something wild, something crazy, something everybody would talk about for days: He bought everyone tickets to the monster truck rally. (And he bought the whole seat, even though we'd only need the edge.)

  • The Old New Thing

    The mysterious stock bitmap: There's no way to summon it, but it shows up in various places


    A number of stock GDI objects are made available by the Get­Stock­Object function, but one stock GDI object that is mysteriously missing is the stock bitmap. You can't summon the stock bitmap, but it manages to show up in various places, some of them perhaps unexpected.

    The stock bitmap is a monochrome 1×1 bitmap which GDI uses in various places where it has to produce a HBITMAP even though there really isn't any bitmap worth speaking of. In other words, it's used when GDI has to return something but would rather return nothing.

    • When you create a memory DC, the current bitmap selected into it is the stock bitmap.
    • When you create a metafile, the current bitmap is the stock bitmap.

    Every DC and metafile has a current bitmap (which you can retrieve with Get­Current­Object), but when GDI creates a brand new DC or metafile, it doesn't know what bitmap the program is going to pass to Select­Object—after all, predicting the future has yet to be perfected. As a placeholder, it sticks in the dummy static bitmap.

    There has to be a bitmap (as opposed to just leaving it NULL), because the Select­Object function returns the previous object or NULL on failure, so there needs to be a way to tell the difference between "I wasn't able to select the bitmap you requested" and "I was able to select the bitmap you requested, but there was no old bitmap." Returning NULL would also break the common coding pattern:

    // select the new bitmap and save the old one
    HBITMAP hbmPrev = SelectObject(hdc, hbmNew);
        ... do something with hdc ...
    // all done - restore the original bitmap
    SelectObject(hdc, hbmPrev);

    If Select­Object had returned NULL when there was no bitmap previously selected into the DC, then the attempt to restore the original bitmap would fail. (Because GDI can't tell whether you passed it a (HBITMAP)NULL or a (HBRUSH)NULL or a (HPEN)NULL or...)

    Normally, a single bitmap cannot be selected into more than one DC, but the stock bitmap has the magical power that it can be selected into multiple DCs at once. Without this magical power, GDI would have to create a different dummy bitmap to select into each newly-created DC and carry it around so that it can be selected back into the DC just before it is destroyed. Seems awful wasteful to allocate an extra bitmap per DC just for this, especially back in the days of 16-bit Windows when GDI heap space was extremely limited.

    There is one more place (that comes to mind) where the stock bitmap appears, and it's somewhat unexpected:

    • When you try to create a 0×y or a x×0 bitmap with the Create­Bitmap or Create­Compatible­Bitmap function you get the stock bitmap back.

    In other words, if you ask for a nothing-bitmap, you get the dummy bitmap back. This is analogous to the case of calling malloc(0), where the implementation is permitted to return a pointer to zero bytes. In other words, malloc(0) can return a non-NULL value which you can't dereference; the only things you can do with it is free() it or realloc() it to something bigger. In the same way that allowing zero-byte allocations simplifies boundary cases of certain algorithms, allowing impossibly thin bitmaps (and returning a dummy handle) may simplify certain graphical algorithms.

    Note however that this behavior of returning the stock bitmap handle when asked to create an impossibly thin bitmap does not apply to the Create­DIB­Section function! If you ask Create­DIB­Section for an impossibly thin bitmap, it returns NULL. So much for consistency.

  • The Old New Thing

    EnumClaw, the function that never was


    bhiggins asks about the mysterious function EnumClaw that existed in some versions of the Win32 documentation.

    I went digging through the MSDN archives and was close to giving up and declaring the cause lost, but then I found it: A copy of the EnumClaw documentation.


    The EnumClaw function returns the child or the parent of the window whose HWND is passed in.

    HWND EnumClaw(
      HWND hwndParent    // handle to parent window
    [in] Handle to the parent window.
    Return Values

    If the function succeeds, the return value is the HWND of the child of the hwndParent window. If the window has no child, the return value is the HWND of the parent of the hwndParent window.

    If the function fails, the return value is NULL. To get extended error information, call GetLastError.


      Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
      Windows 95/98/Me: Unsupported.
      Header: Declared in Winuser.h; include Windows.h.
      Library: Use User32.lib.

    See Also

    Windows Overview, Window Functions.

    There was never a function called EnumClaw. This was a joke inserted by the documentation folks, a pun on the Washington city named Enumclaw. (The state of Washington has a lot of place names which come from Native American words. Other examples are Sequim, Puyallup, and Tulalip. At least Enumclaw is pronounced almost like it's spelled.)

Page 1 of 3 (24 items) 123