Click here to Skip to main content
6,822,613 members and growing! (15,490 online)
Email Password   helpLost your password?
Desktop Development » Shell and IE programming » Shell Programming     Intermediate

Simple shell context menu

By Ralph Arvesen

Demonstrates how to create a simple shell context menu using a few registry entries, instead of COM. The sample context menu creates a grayscale copy of the selected JPEG image.
C#, Windows, .NET, Visual-Studio, Dev
Posted:14 Aug 2006
Views:69,702
Bookmarked:83 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
19 votes for this article.
Popularity: 5.83 Rating: 4.56 out of 5

1

2
1 vote, 5.3%
3
3 votes, 15.8%
4
15 votes, 78.9%
5

Introduction

Shell context menus are displayed when you right click on shell objects such as files and folders. A full-blown context menu is a COM object that implements the IContextMenu and IShellExtInt interfaces. This article demonstrates how to create a simple shell context menu (also called a shortcut menu) that does not require COM and only requires a few registry entries.

Registry entries

You can hookup a context menu to any file type by adding entries under the HKEY_CLASSES_ROOT\<file type>\shell registry location. For example, the following registry script adds the Register and Unregister context menus to DLL files.

REGEDIT4

[HKEY_CLASSES_ROOT\dllfile\shell]
[HKEY_CLASSES_ROOT\dllfile\shell\Register]
[HKEY_CLASSES_ROOT\dllfile\shell\Register\command]
@="regsvr32 \"%L\""

[HKEY_CLASSES_ROOT\dllfile\shell\Unregister]
[HKEY_CLASSES_ROOT\dllfile\shell\Unregister\command]
@="regsvr32 /u \"%L\""

A view of the registry is shown below. The HKEY_CLASSES_ROOT\dllfile\shell key contains the list of context menus for DLL files. The Register and Unregister keys are two of the menus for DLL files (these also specify the menu text since a default value is not specified). The default value of the command key specifies the command line that is executed when the context menu is invoked. The %L argument is a placeholder to the full path of the selected item. You can read more about the registry settings at the MSDN article: Extending Shortcut Menus.

Registering and un-registering

The sample application contains the FileShellExtension class that registers and un-registers a simple shell context menu. The Register method creates the necessary registry entries, and the Unregister method removes the registry entries.

static class FileShellExtension
{
    public static void Register(string fileType,
           string shellKeyName, string menuText, string menuCommand)
    {
        // create path to registry location

        string regPath = string.Format(@"{0}\shell\{1}", 
                                       fileType, shellKeyName);

        // add context menu to the registry

        using (RegistryKey key = 
               Registry.ClassesRoot.CreateSubKey(regPath))
        {
            key.SetValue(null, menuText);
        }

        // add command that is invoked to the registry

        using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(
            string.Format(@"{0}\command", regPath)))
        {
            key.SetValue(null, menuCommand);
        }
    }

    public static void Unregister(string fileType, string shellKeyName)
    {
        Debug.Assert(!string.IsNullOrEmpty(fileType) &&
            !string.IsNullOrEmpty(shellKeyName));

        // path to the registry location

        string regPath = string.Format(@"{0}\shell\{1}", 
                                       fileType, shellKeyName);

        // remove context menu from the registry

        Registry.ClassesRoot.DeleteSubKeyTree(regPath);
    }
}

The sample application self-registers when executed without any command line arguments, or with the -register command; it unregisters when the -unregister command is specified. The usage of the FileShellExtension class is shown below.

// sample usage to register

// get full path to self, %L is a placeholder for the selected file

string menuCommand = string.Format("\"{0}\" \"%L\"", 
                                   Application.ExecutablePath);
FileShellExtension.Register("jpegfile", "Simple Context Menu", 
                            "Copy to Grayscale", menuCommand);

// sample usage to unregister

FileShellExtension.Unregister("jpegfile", "Simple Context Menu");

Creating a grayscale image

The CopyGrayscaleImage method is called when the context menu is clicked. The ColorMatrix class is used to generate a grayscale copy of the selected image.

static void CopyGrayscaleImage(string filePath)
{
    // full path to the grayscale copy

    string grayFilePath = Path.Combine(
        Path.GetDirectoryName(filePath),
        string.Format("{0} (grayscale){1}",
        Path.GetFileNameWithoutExtension(filePath),
        Path.GetExtension(filePath)));

    // using calls Dispose on the objects, important

    // so the file is not locked when the app terminates

    using (Image image = new Bitmap(filePath))
    using (Bitmap grayImage = new Bitmap(image.Width, image.Height))
    using (Graphics g = Graphics.FromImage(grayImage))
    {
        // setup grayscale matrix

        ImageAttributes attr = new ImageAttributes();
        attr.SetColorMatrix(new ColorMatrix(new float[][]{
            new float[]{0.3086F,0.3086F,0.3086F,0,0},
            new float[]{0.6094F,0.6094F,0.6094F,0,0},
            new float[]{0.082F,0.082F,0.082F,0,0},
            new float[]{0,0,0,1,0,0},
            new float[]{0,0,0,0,1,0},
            new float[]{0,0,0,0,0,1}}));

        // create the grayscale image

        g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height),
            0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attr);

        // save to the file system

        grayImage.Save(grayFilePath, ImageFormat.Jpeg);
    }
}

The original and generated grayscale images are shown below:

Running the sample

The sample was built with Visual Studio 2005, and requires the .NET Framework 2.0; however, the ideas can easily be incorporated into any .NET version and language. You can do the following to run the sample:

  • Build and run the application. This registers the context menu by adding the HKEY_CLASSES_ROOT\jpegfile\shell\Simple Context Menu key to the registry.
  • Right click on a JPEG file, you should see a new Copy to Grayscale context menu.
  • Click the context menu to create a grayscale copy of the image.
  • Unregister the context menu by running SimpleContextMenu.exe �unregister.

Context menus for all files, folders, and drives

You can also hookup context menus to all files, folders, and drives by adding entries to the file type's *, Directory, and Drive registry keys. For example, XP PowerToys adds the Open Command Window Here menu to all folders with the following registry script:

REGEDIT4

[HKEY_CLASSES_ROOT\Directory\shell\cmd]
@="Open Command Window Here"

[HKEY_CLASSES_ROOT\Directory\shell\cmd\command]
@="cmd.exe /k \"cd %L\""

Simple context menus do have limitations, such as only accepting one file on the command line, but they are still pretty useful. I'll cover creating a full-blown .NET COM-based context menu in a future article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Ralph Arvesen


Member
Ralph Arvesen is a software engineer for Vertigo Software and has worked on desktop, web and Pocket PC applications using .NET and C++. Before Vertigo, he designed hardware and firmware for optical inspection systems and has been developing software for the Microsoft platform since Windows 2.0. He co-authored several books and worked as technical editor on others. Ralph lives in the Texas Hill Country west of Austin; his personal site is located at www.lostsprings.com.
Occupation: Web Developer
Location: United States United States

Other popular Shell and IE programming articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 40 (Total in Forum: 40) (Refresh)FirstPrevNext
GeneralGreat Job! Pinmemberoldsellerros12:32 17 Nov '09  
GeneralWhat about custom icon? PinmemberWizard_Memfis11:48 2 Sep '09  
QuestionThe * didn't works well ??? PinmemberAdore C++10:18 13 Jun '09  
GeneralDoesn't work in Vista64bit PinmemberGreg Cadmes19:39 22 Jan '09  
GeneralRegistry shell command for dll not working on vista PinmemberPaul Shaffer21:13 15 Jan '09  
GeneralExcellent Example !!! Pinmemberfer_cyberlinklabs9:46 8 Oct '08  
GeneralUsing this with a .wav file PinmemberJason Coggins3:17 8 Sep '08  
GeneralRe: Using this with a .wav file PinmemberSuleyman Arslan11:29 7 Oct '08  
QuestionHow add conditionally enable context menu PinmemberAltaf Navalur21:30 27 Jun '08  
QuestionHow to make multiple file selections? Pinmembermasfenix12:46 9 Apr '08  
AnswerRe: How to make multiple file selections? Pinmemberdhsc5:20 22 Oct '09  
GeneralRe: How to make multiple file selections? PinmemberPham Huy Anh2:28 27 Jan '10  
GeneralRegistry Entry throught Setup And Deployment Project PinmemberMohantaD7:55 23 Nov '07  
QuestionRe: Registry Entry throught Setup And Deployment Project Pinmemberadriaan van heerden3:24 16 Oct '08  
GeneralPlease help PinmemberAbhishek sur3:52 16 Oct '07  
GeneralVista PinmemberDanauktion.net0:44 30 Sep '07  
GeneralRe: Vista PinmemberPhilipTyphe20:16 28 Feb '08  
GeneralRe: Vista Pinmemberneo2-0x@o2.pl4:40 27 Jul '08  
GeneralDesktop Context item? Pinmemberstudent_rhr6:54 22 Jul '07  
GeneralNo context menu PinmemberTOMCAT814:59 26 Feb '07  
QuestionAdd sub-menu item under "SendTo..." Pinmemberdfererer17:16 16 Feb '07  
AnswerRe: Add sub-menu item under "SendTo..." Pinmemberradialronnie6:44 29 May '08  
GeneralRe: Add sub-menu item under "SendTo..." Pinmemberdfer10:38 29 May '08  
QuestionRegistry Privileges Pinmembersheijin22:28 5 Feb '07  
GeneralHelp- Not getting context menu [modified] PinmemberVenkatesh.P19:59 1 Jan '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.

PermaLink | Privacy | Terms of Use
Last Updated: 14 Aug 2006
Editor: Smitha Vijayan
Copyright 2006 by Ralph Arvesen
Everything else Copyright © CodeProject, 1999-2010
Web21 | Advertise on the Code Project