Tuesday, March 13, 2007

Shell Extensions - Context Menu

I couldn’t blog for long time due to some personal reasons. Hope I’ll be able to blog without any breaks in future. I'm going to write something different this time, Context Menu for explorer.

I wanted to write a context menu extension for the explorer using some Win32 API calls, which took me a while and it was really a pain. Had problems in debugging, needed to reboot the machine number of times, etc… So thought of coming up with a wrapper in .NET. The wrapper is mainly an abstract class which can be driven to create a personalized context menu extension. The assembly can be downloaded from
here and the source can be downloaded from here.

How To use Utils.ShellExtensions.ContextMenu.dll

Deploy Utils.ShellExtensions.ContextMenu.dll in gac. Create a class library project. Add Utils.ShellExtensions.ContextMenu.dll to your project. Drive a class from BaseContextMenu. Make it com visible, install it in gac and register it for com.


Example


[ComVisible(true), Guid("0056DA96-FFD6-4180-BAB2-8C9B6F552B2D")]
public class MyMenu : BaseContextMenu
{
     [ComRegisterFunction]
     public static void RegisterFunction(Type t)
     {
          //Register for files
          RegisterContextMenu.Register("*", t.GUID);
          //Register for folders
          RegisterContextMenu.Register("Directory", t.GUID);
          //Register for drives
          RegisterContextMenu.Register("Drive", t.GUID);
     }

     [ComUnregisterFunction]
     public static void UnregisterFunction(Type t)
     {
          RegisterContextMenu.Unregister("*", t.GUID);
          RegisterContextMenu.Unregister("Directory", t.GUID);
          RegisterContextMenu.Unregister("Drive", t.GUID);
     }

     public override void AssembleMenu()
     {
          System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(@"c:\test.bmp");
          System.Drawing.Bitmap bmp1 = new System.Drawing.Bitmap(@"c:\test1.bmp");
          MenuItems menuItems1 = new MenuItems("Test1",0,false);
          MenuItems menuItems2 = new MenuItems("Test2",1,false,bmp,true);
          MenuItems menuItems3 = new MenuItems("Test3",2,false,bmp1,false);
          menuItems2.Click +=new Utils.ShellContextMenu.MenuItems.MenuClickHandler(menuItems2_Click);
          menuItems3.Click +=new Utils.ShellContextMenu.MenuItems.MenuClickHandler(menuItems3_Click);
          //This order is important. Always insert the parent container and then the child!
          InsertMenu(menuItems1);
          AddMenu(menuItems1, menuItems2);
          AddMenu(menuItems1, menuItems3);
     }

     private void menuItems2_Click()
     {
          System.Windows.Forms.MessageBox.Show("Menu Test2 clicked");
     }

     private void menuItems3_Click()
     {
          System.Windows.Forms.MessageBox.Show("Menu Test3 clicked");
     }
}

Labels: , ,