C is for cookie, that's good enough for me

Hmm, I've been slacking off a bit on the blog, haven't I. Oh well, time to delve back into another VSIP lesson. In addition to package loading and getting/calling services provided by the environment and other packages, cookies are also a pretty important concept in VSIP.

A cookie in short is an unsigned integer (uint) that the shell gives your package when it asks to listen for a certain kind of event. When your package is done listening, you give the cookie back. It's that simple, but it's a pretty important concept for packages that want to respond to certain events.

Let’s take a look at an example. Suppose that I’m working in C# (of course) and that  want to be notified any time that there are changes to the running document table (RDT). (The RDT is a list of the currently opened documents in VS). I could do something like this in my Package class:

 

protected IVsRunningDocumentTable runningDocService;

protected uint rdtCookie;

 

protected override void Initialize()

{

runningDocService = this.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;

      runningDocService.AdviseRunningDocTableEvents(new RDTListener(), rdtCookie);

}

The RDTListener object I passed in is a class I wrote that implements IVsRunningDocTableEvents3. Whenever one of the events occurs, the appropriate method is called in my RDTListener object. Whenever I am done listening for events, I can simply call that corresponding Unadvise() method from SVsRunningDocumentTable and return my cookie to let the environment know that I don’t care about any more events.

In the Managed Package Framework, the classes will use the more typical (and simple) .NET model of events and implementing event handlers.