Click here to Skip to main content
15,879,535 members
Articles / Programming Languages / C#
Article

Simple shell context menu

Rate me:
Please Sign up or sign in to vote.
4.82/5 (37 votes)
14 Aug 20062 min read 354.3K   5.7K   140   55
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.

Image 1

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.

Image 2

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.

C#
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.

C#
// 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.

C#
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:

Image 3

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


Written By
Web Developer
United States United States
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.

Comments and Discussions

 
PraiseFine on Windows 8 - 64 bit Pin
marft21-Jul-18 23:08
marft21-Jul-18 23:08 
General Pin
Member 1258772211-Dec-17 22:28
Member 1258772211-Dec-17 22:28 
QuestionNo effect for Windows 7 Pro 64-bit Pin
Mike_Finch29-Jun-17 13:57
Mike_Finch29-Jun-17 13:57 
AnswerRe: No effect for Windows 7 Pro 64-bit Pin
EM3R50N8-Aug-18 12:23
EM3R50N8-Aug-18 12:23 
QuestionUnauthorizedAccessException was unhandled Pin
Member 113632043-Feb-15 23:51
Member 113632043-Feb-15 23:51 
AnswerRe: UnauthorizedAccessException was unhandled Pin
Member 1134503524-Jul-15 10:54
Member 1134503524-Jul-15 10:54 
GeneralMy vote of 5 Pin
Agent__00721-Jan-15 18:44
professionalAgent__00721-Jan-15 18:44 
QuestionHow can i implement in WPF Pin
karthikin15-Mar-14 7:13
karthikin15-Mar-14 7:13 
QuestionAccess denied Pin
Mojtaba026-Jan-14 1:36
Mojtaba026-Jan-14 1:36 
GeneralMy vote of 5 Pin
Lord Codemonger3-May-13 8:59
Lord Codemonger3-May-13 8:59 
QuestionHow to save excel file path? Pin
Khuc Manh Thao28-Feb-12 15:52
Khuc Manh Thao28-Feb-12 15:52 
QuestionHow to make work on 64-bit? Pin
Member 30938448-Dec-11 3:45
Member 30938448-Dec-11 3:45 
QuestionOn WinXP fine | On Win7 it does not work Pin
DiabloPB16-Oct-11 22:09
DiabloPB16-Oct-11 22:09 
QuestionHow do you do this for a custom file type e.g. *.ttr files Pin
kommand17-Nov-10 6:36
kommand17-Nov-10 6:36 
GeneralGreat Job! Pin
Alex Manolescu17-Nov-09 11:32
Alex Manolescu17-Nov-09 11:32 
QuestionWhat about custom icon? Pin
Wizard_Memfis2-Sep-09 10:48
Wizard_Memfis2-Sep-09 10:48 
QuestionThe * didn't works well ??? Pin
AhmedOsamaMoh13-Jun-09 9:18
AhmedOsamaMoh13-Jun-09 9:18 
GeneralDoesn't work in Vista64bit Pin
Greg Cadmes22-Jan-09 18:39
Greg Cadmes22-Jan-09 18:39 
Too bad more R&D wasn't done to elaborate on why the context menu item doesn't appear. (Even if the register/unregister was sucessful)

Did anyone else get this to work in Vista?
GeneralRegistry shell command for dll not working on vista Pin
Paul Shaffer15-Jan-09 20:13
Paul Shaffer15-Jan-09 20:13 
GeneralExcellent Example !!! Pin
fer_cyberlinklabs8-Oct-08 8:46
fer_cyberlinklabs8-Oct-08 8:46 
GeneralUsing this with a .wav file Pin
Jason Coggins8-Sep-08 2:17
Jason Coggins8-Sep-08 2:17 
GeneralRe: Using this with a .wav file Pin
Suleyman Arslan7-Oct-08 10:29
Suleyman Arslan7-Oct-08 10:29 
QuestionHow add conditionally enable context menu Pin
Altaf Navalur27-Jun-08 20:30
Altaf Navalur27-Jun-08 20:30 
QuestionHow to make multiple file selections? Pin
masfenix9-Apr-08 11:46
masfenix9-Apr-08 11:46 
AnswerRe: How to make multiple file selections? Pin
dhsc22-Oct-09 4:20
dhsc22-Oct-09 4:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

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