• The Old New Thing

    Dragging a shell object, part 3: Detecting an optimized move

    • 4 Comments

    We were considering how to detect that the drag/drop operation resulted in a conceptual Move even if the DROPEFFECT_MOVE was optimized away.

    If the drop target is the shell, you can query the data object for CFSTR_PERFORMEDDROPEFFECT to see what the performed effect was.

    void OnLButtonDown(HWND hwnd, BOOL fDoubleClick,
                       int x, int y, UINT keyFlags)
    {
      ...
            if (dwEffect & DROPEFFECT_MOVE) {
              DeleteFileW(wszPath);
            }
            CheckPerformedEffect(hwnd, pdto);
      ...
    }
    

    Of course, we need that CheckPerformedEffect function too.

    void CheckPerformedEffect(HWND hwnd, IDataObject *pdto)
    {
      FORMATETC fe = {
         (CLIPFORMAT)RegisterClipboardFormat(CFSTR_PERFORMEDDROPEFFECT),
         NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
      STGMEDIUM stgm;
      if (SUCCEEDED(pdto->GetData(&fe, &stgm))) {
        if ((stgm.tymed & TYMED_HGLOBAL) &&
            GlobalSize(stgm.hGlobal) >= sizeof(DWORD)) {
           DWORD *pdw = (DWORD*)GlobalLock(stgm.hGlobal);
           if (pdw) {
             if (*pdw == DROPEFFECT_MOVE) {
                MessageBox(hwnd, TEXT("Moved"), TEXT("Scratch"), MB_OK);
             }
             GlobalUnlock(stgm.hGlobal);
           }
        }
        ReleaseStgMedium(&stgm);
      }
    }
    

    If the item is dropped on a shell window, the drop target will set data into the data object under the clipboard format name CFSTR_PERFORMEDDROPEFFECT. The data takes the form of a DWORD in an HGLOBAL, and the value is the actual drop effect before any optimizations kicked in.

    Here, we check whether it was a DROPEFFECT_MOVE and display a special message if so.

  • The Old New Thing

    It is not illegal to use James Bond style tactics for winning at the roulette wheel

    • 10 Comments

    In an operation straight out of a James Bond movie, a trio of gamblers used a laser range-finder hidden in a mobile phone to predict the likeliest landing spot of a roulette ball, reducing the odds from 37-1 to 6-1.

    Scotland Yard concluded that they did nothing illegal and were allowed to keep their winnings.

    I wonder how long it'll be before this device shows up on Engadget.

    (Once I discovered that I was scooped by Slashdot, I figured there was no hurry and held the story for a quiet day.)

  • The Old New Thing

    Researchers find connection between lack of sleep and weight gain

    • 31 Comments
    Shortage of sleep is linked to obesity, according to research published yesterday.

    Lack of sleep boosts levels of a hormone that triggers appetite and lowers levels of a hormone that tells your body it is full according to the team. The scientists will now study whether obese people should sleep more to lose weight.
  • The Old New Thing

    Dragging a shell object, part 2: Enabling the Move operation

    • 24 Comments

    Let's say that we did want to support Move in our drag/drop program, for whatever reason. Let's do it with some scratch file instead of clock.avi, though. Create a file somewhere that you don't mind losing; let's say it's C:\throwaway.txt. Change the function OnLButtonDown as follows:

    void OnLButtonDown(HWND hwnd, BOOL fDoubleClick,
                       int x, int y, UINT keyFlags)
    {
      IDataObject *pdto;
      if (SUCCEEDED(GetUIObjectOfFile(hwnd,
                        L"C:\\throwaway.txt",
                        IID_IDataObject, (void**)&pdto))) {
        IDropSource *pds = new CDropSource();
        if (pds) {
          DWORD dwEffect;
          if (DoDragDrop(pdto, pds,
                     DROPEFFECT_COPY | DROPEFFECT_LINK | DROPEFFECT_MOVE,
                     &dwEffect) == DRAGDROP_S_DROP) {
            if (dwEffect & DROPEFFECT_MOVE) {
              DeleteFile(TEXT("C:\\throwaway.txt"));
            }
          }
          pds->Release();
        }
        pdto->Release();
      }
    }
    

    Oh wait, there are people out there who think I'm advocating hard-coded paths, so let me change the program to operate on a path passed on the command line. This is code that is purely a distraction from the point of this article, which is why I avoided it originally. Personally I dislike it when somebody hands me a sample program that is 90% unrelated to the technology the program is trying to demonstrate. I have to go digging through the code hunting for the 10% of stuff that matters.

    #include <shellapi.h>
    
    LPWSTR *g_argv;
    LPCWSTR g_pszTarget;
    
    void OnLButtonDown(HWND hwnd, BOOL fDoubleClick,
                       int x, int y, UINT keyFlags)
    {
      IDataObject *pdto;
      if (SUCCEEDED(GetUIObjectOfFile(hwnd,
                        g_pszTarget,
                        IID_IDataObject, (void**)&pdto))) {
      ...
              DeleteFileW(g_pszTarget);
      ...
    }
    
    BOOL
    InitApp(void)
    {
      int argc;
      g_argv = CommandLineToArgvW(GetCommandLineW(), &argc);
      if (!g_argv || argc != 2) return FALSE;
      g_pszTarget = g_argv[1];
      if (PathIsRelative(g_pszTarget)) return FALSE;
      ...
    }
    

    Woo-hoo, eight distracting lines of code that have nothing to do with the subject of dragging shell objects around. I hope you're happy.

    Where was I? Oh right, explaining the first batch of blue code that by now has scrolled off your screen thanks to the intervening meaningless drivel.

    Now that we allow move, we need to check whether the resulting effect was DROPEFFECT_MOVE, which tells us, "The drop target wanted to perform a move operation, but it only got as far as copying the object; please finish the move operation by deleting the original."

    Notice that DROPEFFECT_MOVE does not mean, "The drop target performed a move." Rather, it tells you that the drop target wants you to delete the original. If the drop target was able to delete the original (or move it directly), then you will not get DROPEFFECT_MOVE back.

    (One case where DROPEFFECT_MOVE doesn't even mean that a Move operation occurred at all is if the user dragged the object to an "Incinerator" icon, the purpose of which is to destroy whatever is dropped onto it. In this case the Incinerator would return DROPEFFECT_MOVE without even making a copy. Result: The object is deleted. A better name for DROPEFFECT_MOVE would have been DROPEFFECT_DELETEORIGINAL.)

    If the data object represents a file, then the shell is pretty good at figuring out how to move the file to the destination instead of copying it and asking you to delete the original. You will typically get DROPEFFECT_MOVE back only if the data object represents a non-file, since in that case the shell doesn't know how to delete the original.

    But what if you want to know whether the operation was a move, regardless of whether the operation was optimized by the drop target? We'll look at that next time.

    (By the way, if you execute a Move of the throwaway file, don't forget to move it back so you can run the scratch program again!)

  • The Old New Thing

    Dragging a shell object, part 1: Getting the IDataObject

    • 20 Comments

    The shell gives you the IDataObject; all you have to do is drag it around. (This is the first of a five-part series.)

    Start with the scratch program, and add the function GetUIObjectOfFile from an earlier article. Also, change the calls to CoInitialize and CoUninitialize to OleInitialize and OleUninitialize, respectively, since we're now going to be using full-on OLE and not just COM.

    In order to initiate a drag/drop operation, we need a drop source:

    class CDropSource : public IDropSource
    {
    public:
      // *** IUnknown ***
      STDMETHODIMP QueryInterface(REFIID riid, void **ppv);
      STDMETHODIMP_(ULONG) AddRef();
      STDMETHODIMP_(ULONG) Release();
    
      // *** IDropSource ***
      STDMETHODIMP QueryContinueDrag(BOOL fEscapePressed, DWORD grfKeyState);
      STDMETHODIMP GiveFeedback(DWORD dwEffect);
    
      CDropSource() : m_cRef(1) { }
    private:
      ULONG m_cRef;
    };
    
    HRESULT CDropSource::QueryInterface(REFIID riid, void **ppv)
    {
      IUnknown *punk = NULL;
      if (riid == IID_IUnknown) {
        punk = static_cast<IUnknown*>(this);
      } else if (riid == IID_IDropSource) {
        punk = static_cast<IDropSource*>(this);
      }
    
      *ppv = punk;
      if (punk) {
        punk->AddRef();
        return S_OK;
      } else {
        return E_NOINTERFACE;
      }
    }
    
    ULONG CDropSource::AddRef()
    {
      return ++m_cRef;
    }
    
    ULONG CDropSource::Release()
    {
      ULONG cRef = --m_cRef;
      if (cRef == 0) delete this;
      return cRef;
    }
    
    HRESULT CDropSource::QueryContinueDrag(
              BOOL fEscapePressed, DWORD grfKeyState)
    {
      if (fEscapePressed) return DRAGDROP_S_CANCEL;
    
      // [Update: missing paren repaired, 7 Dec]
      if (!(grfKeyState & (MK_LBUTTON | MK_RBUTTON)))
        return DRAGDROP_S_DROP;
    
      return S_OK;
    }
    
    HRESULT CDropSource::GiveFeedback(DWORD dwEffect)
    {
      return DRAGDROP_S_USEDEFAULTCURSORS;
    }
    

    As you can see, this drop source is extraordinarily boring. Even the interesting methods are uninteresting.

    The IDropSource::QueryContinueDrag method is pretty much boilerplate. If the Escape key was pressed, then cancel the drag/drop operation. If the mouse buttons are released, then complete the operation. Otherwise, continue the operation.

    The IDropSource::GiveFeedback method is even less interesting. It merely returns DRAGDROP_S_USEDEFAULTCURSORS to indicate that it wants default drag feedback.

    Believe it or not, we now have everything we need to drag a file.

    void OnLButtonDown(HWND hwnd, BOOL fDoubleClick,
                       int x, int y, UINT keyFlags)
    {
      IDataObject *pdto;
      // In a real program of course
      // you wouldn't use a hard-coded path.
      // [comment added 11am because apparently some
      // people thought this wasn't self-evident.]
      if (SUCCEEDED(GetUIObjectOfFile(hwnd,
                        L"C:\\Windows\\clock.avi",
    		    IID_IDataObject, (void**)&pdto))) {
        IDropSource *pds = new CDropSource();
        if (pds) {
          DWORD dwEffect;
          DoDragDrop(pdto, pds, DROPEFFECT_COPY | DROPEFFECT_LINK,
                     &dwEffect);
          pds->Release();
        }
        pdto->Release();
      }
    }
    
        HANDLE_MSG(hwnd, WM_LBUTTONDOWN, OnLButtonDown);
    

    To drag an object, you need two things, a data object and a drop source. We created our drop source above, and the data object comes from the shell. All that's left to do is start the drag/drop operation by calling the DoDragDrop function.

    Notice that we specify that the permitted operations are DROPEFFECT_COPY and DROPEFFECT_LINK. We specifically disallow DROPEFFECT_MOVE because this program doesn't present a folder-like window; the user has no expectation that the drag/drop will result in a Move operation.

    Next time, adding Move support, just to see how it works.

  • The Old New Thing

    Why are documents printed out of order when you multiselect and choose "Print"?

    • 26 Comments

    If you select say five files and then right-click them and choose "Print", they tend to print in a random order. Why is that?

    The shell invokes the Print verb on each file in turn, and depending on how the program responsible for printing the document is registered, one of several things can happen.

    • Most commonly, the program that prints the document registered a simple command line under the shell\print\command registry key. In this case, the program is launched five times, each with a different file. All these print commands are now racing to the printer and it's a question of which copy of the program submits its print job first that determines the order in which they come out of the printer. (You're probably going to see the shortest and simplest documents come out first since they take less time to render.)
    • Occasionally, the program that prints the document registered a DDE verb under the shell\print\ddeexec registry key. In this case, one copy of the program is launched and it is given each filename one at a time. What it does with those filenames is now up to the program. If the program supports background printing, it will probably shunt the printing of the document onto a background thread, and now you're roughly in the same fix as the previous scenario: Five background threads each racing to see who can submit their print job first.
    • Extremely rarely, the program that prints the document registered a drop handler under the shell\print\DropTarget key. In this case, the drop target is instantiated and is given the list of files. It is then up to the drop target to decide what to do with the documents.

    These three ways of registering print actions are described in the MSDN documentation on verbs and file associations.

    [Update: 7:30am, fixed title.]

  • The Old New Thing

    Why did Windows 95 run the timer at 55ms?

    • 32 Comments

    The story behind the 55ms timer tick rate goes all the way back to the original IBM PC BIOS. The original IBM PC used a 1.19MHz crystal, and 65536 cycles at 1.19MHz equals approximately 55ms. (More accurately, it was more like 1.19318MHz and 54.92ms.)

    But that just pushes the question to another level. Why 1.19...MHz, then?

    With that clock rate, 216 ticks equals approximately 3600 seconds, which is one hour. (If you do the math it's more like 3599.59 seconds.) [Update: 4pm, change 232 to 216; what was I thinking?]

    What's so special about one hour?

    The BIOS checked once an hour to see whether the clock has crossed midnight. When it did, it needed to increment the date. Making the hourly check happen precisely when a 16-bit tick count overflowed saved a few valuable bytes in the BIOS.

    Another reason for the 1.19MHz clock speed was that it was exactly one quarter of the original CPU speed, namely 4.77MHz, which was in turn 4/3 times the NTSC color burst frequency of 3.5MHz. Recall that back in these days, personal computers sent their video output to a television set. Monitors were for the rich kids. Using a timer related to the video output signal saved a few dollars on the motherboard.

    Calvin Hsia has another view of the story behind the 4.77MHz clock.

    (Penny-pinching was very common at this time. The Apple ][ had its own share of penny-saving hijinks.)

  • The Old New Thing

    What is the purpose of the bmPlanes member of the BITMAP structure?

    • 21 Comments

    Many bitmap-related structures in Windows have a field called "planes". For example the BITMAPINFOHEADER structure has a biPlanes member (which must be set to 1). The BITMAP structure has a field called bmPlanes. What's the deal with that field?

    The EGA video adapter supported 16 simultaneous colors. This was an enormous improvement over the CGA, which supported only four colors. If you have 16 colors, then you need four bits per pixel. You would think that the encoding would be to have the each byte of video memory encode two pixels, one in the bottom four bits and one in the top four. But for technical reasons, the structure of video memory was not that simple.

    Instead of putting the bits for a single pixel next to each other, the color channels were each split into their own monochrome bitmap. In other words, the pixels were sliced "the other way":

    0 0 0 0 1 1 1 1 | 0F
    0 0 1 1 0 0 1 1 | 33
    0 1 0 1 0 1 0 1 | 55
    0 1 1 0 0 1 1 0 | 66

    0 3 5 6 8 B D E

    Suppose you wanted to display eight pixels, with colors { 0, 3, 5, 6, 8 B, D, E } above. Instead of storing the nibbles in that order, slice the nibbles apart into their component bits and collect all the bits from the same position together. In other words, read the bits across rather than down.

    In the default 16-color palette, the colors were assigned so that bit 0 was the blue channel, bit 1 was the green channel, bit 2 was the red channel, and bit 3 was the intensity channel. With this interpretation, the four slices can be interpreted as the "intensity plane", the "red plane", the "green plane" and the "blue plane". For the last three planes, you can imagine that each one represents what you would see if only the corresponding electron gun were firing.

    Since this was the native color format for EGA, there needed to be a way to express this color format in the BITMAP structure so that device-dependent bitmaps could be represented by Windows.

    Thus was born the planar color format. For 16-color planar bitmaps, the number of planes is four and the number of bits per pixel is one.

  • The Old New Thing

    What's the difference between GetKeyState and GetAsyncKeyState?

    • 14 Comments

    I've seen some confusion over the difference between the GetKeyState function and the GetAsyncKeyState function.

    GetKeyState returns the virtual key state. In other words, GetKeyState reports the state of the keyboard based on the messages you have retrieved from your input queue. This is not the same as the physical keyboard state:

    • If the user has typed ahead, GetKeyState doesn't report those changes until you use the PeekMessage function or the GetMessage function to retrieve the message from your input queue.

    • If the user has switched to another program, then the GetKeyState function will not see the input that the user typed into that other program, since that input was not sent to your input queue.

    When should you use GetKeyState and when should you use GetAsyncKeyState?

    For user interface work, you nearly always want GetKeyState.

    If you are responding to an input message and want to know what keys were pressed at the time that input was generated, then you want to use GetKeyState. For example, if you want to distinguish a left-click of the mouse from an Alt+LeftClick, you must use GetKeyState to query the state of the Alt key (known as VK_MENU for historical reasons). That's because you want to know whether the Alt key was down when the user clicked the mouse, not whether the key is down this very instant. Whether the user released the Alt key between the time they clicked and the time you processed the message is irrelevant. You care that the Alt key was down at the time of the click.

    Note that if you are implementing a context menu handler, then you shouldn't be using either GetKeyState or GetAsyncKeyState, because the context menu can be invoked programmatically without any user action. For IContextMenu::QueryContextMenu, you should test for the CMF_EXTENDEDVERBS flag to detect whether you should display extended commands rather than querying the keyboard directly. Similarly, for IContextMenu::InvokeCommand, you should be testing the CMIC_MASK_CONTROL_DOWN and CMIC_MASK_SHIFT_DOWN flags if you want to alter your behavior based on the shift states.

    Given this primer on the difference between GetKeyState and GetAsyncKeyState, you can now explain the behavior this user is seeing.

    [Updated: 1 Dec 2004, minor typo.]

  • The Old New Thing

    Why doesn't the RunAs program accept a password on the command line?

    • 57 Comments

    The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?

    This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.

    In other words, the feature is missing to remove the temptation to use the feature insecurely.

    If this offends you and you want to be insecure and pass the password on the command line anyway (for everyone to see in the command window title bar), you can write your own program that calls the CreateProcessWithLogonW function.

    (I'm told that there is a tool available for download which domain administrators might find useful, though it solves a slightly different problem.)

Page 368 of 427 (4,265 items) «366367368369370»