Windows Explorer has a default implementation for IContextMenu commonly called DefCM that has been used since Win95. It has many clients and has evolved over time, of course, but its primary focus has always been to support the most important of shell folders: File System Folder. A big part of this support revolves around extensibility. Raymond has been talking about hosting IContextMenu, I am going to talk about how IContextMenu extensions interact with DefCM. And while I may call out the behavior of older versions of Windows to explain things, I am going to focus on the behavior of WinXP.

The first thing to read is Verbs and File Associations on MSDN. The section on "Static vs. Dynamic Verbs" explains that there are really two extensibility methods. this is important since they will be aggregated together by DefCM.  DefCM enumerates verbs from a set of registry hkeys typically generated from file associations. For more details about these keys look here.

DefCM starts by gathering all of the IContextMenu extensions which are registered under the "shellex\contextmenuhandlers" subkeys. There is also one implicit object for file associations that handles static verb registration which is added first. The result of this enumeration is an array of objects starting with the static verb implementation, followed by each of the registered ContextMenuHandlers in order of the keys above.  Handlers that are registered under two keys are pruned to a single entry.

In order to get the expected menu order, DefCM calls QueryContextMenu() on each of these objects to insert verbs in reverse order, and has each one insert at the top of the menu (zeroth position). As a result the static verbs are inserted last and end up at the top, which is good since usually these guys are the default.

So the sorting is based on the following elements in decision order:

  1. Key priority (eg, txtfile, *, AFSO)
  2. Registry Enumeration order of shellex\contextmenuhandlers with a special case for static verbs always being first
  3. IContextMenu Implementation order

So if there is any contention for position, there is no consistent way for an extension to guarantee their relative position within the menu.