My own preface explains:
The original author is Dave Kerr, the original link to the. NET Shell Extensions-shell Context Menus, I was in order to complete the latest needs of the time when the query information found, because too long have not read foreign materials, So in order to exercise the translation, there is a sentence in the text could not be translated.
- Download Sharpshell source code-1.8 MB
- Download Sharpshell Tools-181.1 KB
- Download Sharpshell Core library-90.9 KB
Introduction:
Until. NET 4.0, we still can't get through. NET code fully implements the functionality of the shell extension. But as the framework continues to improve, we can now implement this functionality. In this article, I'll take you through the C # class file to quickly implement the right-click menu Extension feature.
(The figure is a feature that has been implemented, "Count Lines" is a right-click option that I have customized, and the article will explain carefully how to do that)
“. NET Shell Extensions index:
This article is just ". NET shell extension, this series also includes:
- . NET Shell Extensions-shell Context Menus
- . NET Shell Extensions-shell Icon handlers
- . NET Shell Extensions-shell Info Tip handlers
- . NET Shell Extensions-shell Drop handlers
- . NET Shell Extensions-shell Preview handlers
- . NET Shell Extensions-shell Icon Overlay handlers
- . NET Shell Extensions-shell Thumbnail handlers
- . NET Shell Extensions-shell Property Sheets
- . NET Shell extensions-deploying Sharpshell Servers
What is Shell Context Menus?
Shell context menus is a COM server registered in the system that allows the Context menu of the Shell object to be extended. The objects mentioned here can be defined to specific file types, such as ". txt" files, drivers, files, or other file types. The context menu now provides quick access to more information through Windows Manager.
Get ready:
There is a lot of work to do to implement shell extensions: we need to implement specific COM interfaces, need to provide services, and update the registry in a variety of ways. Now we can invoke a library called "Sharpshell" that I've written to do these complex functions, so that our task becomes simply to create a lightweight class library that contains the completed extended functionality class.
Our goal:
The code shown below creates a shell extension that allows you to calculate the number of rows in any text file by right-clicking and selecting "Count Lines". In the second half of the article I will explain in detail how to create the libraries shown below. The intention of me to display the code first is to emphasize how to complete the writing of the library in a straightforward way when calling the Sharpshell library.
/// <summary>///The countlinesextensions is an example shell context menu extension,///implemented with Sharpshell. It adds the command ' Count Lines ' to text///files./// </summary>[ComVisible (true)][comserverassociation (associationtype.classofextension,". txt")] Public classcountlinesextension:sharpcontextmenu{/// <summary> ///Determines whether this instance can a shell///context Show menu, given the specified selected file list. /// </summary> /// <returns> /// <c>true</c>If this instance should show a shell context///menu for the specified file list; otherwise,<c>false</c>. /// </returns> protected Override BOOLCanshowmenu () {//We always show the menu. return true; } /// <summary> ///creates the context menu. This can is a single menu item or a tree of them. /// </summary> /// <returns> ///The context menu for the shell context menu. /// </returns> protected OverrideContextMenuStrip CreateMenu () {//Create the menu strip. varmenu =NewContextMenuStrip (); //Create a ' count lines ' item. varItemcountlines =NewToolStripMenuItem {Text="Count Lines ...", Image=Properties.Resources.CountLines}; //When We click, we ' ll count the lines.Itemcountlines.click + = (sender, args) =Countlines (); //ADD the item to the context menu.menu. Items.Add (Itemcountlines); //Return to the menu. returnmenu; } /// <summary> ///Counts the lines in the selected files. /// </summary> Private voidCountlines () {//Builder for the output. varBuilder =NewStringBuilder (); //Go through each file. foreach(varFilePathinchselecteditempaths) { //Count the lines.Builder. Appendline (string. Format ("{0}-{1} Lines", Path.getfilename (FilePath), File.ReadAllLines (FilePath). Length)); } //Show the ouput.MessageBox.Show (builder. ToString ()); }}
The code can be said to be simple and clear, so let's start with a closer look at the specific implementation process.
First step: Create a new project
First, we need to start a new C # class library project.
Tip: You can also use VB in addition to C #, although all of the code in this article is C #, but the principle of the method is equally available.
In this example, our project name is "Countlinesextension".
Now we need to add a reference:
- System.Windows.Forms
- System.Drawing
System.Windows.Forms
This is necessary because we need to define the context menu through WinForms ContextMenuStrip. The reason to call System.Drawing is that we want to use icons.
Rename 'Class1.cs' to 'CountLinesExtension.cs'. So now our project has become this:
Step two: Quoting Sharpshell
Now we need to add a reference to the Sharpshell. Here are some of the different ways you can:
To add a reference:
Download the ' Sharpshell Library ' zip file at the beginning of the article, and then add a reference directly to the SharpShell.dll file.
Tip: The article begins the download file is written in this article when the file, if you want to get the latest version, please get through nuget or from sharpshell.codeplex.com.
Nuget
If you have nuget on your computer, simply retrieve the Sharpshell and install it, or go directly to: Https://www.nuget.org/packages/SharpShell
CodePlex
You can get the latest version directly from the CodePlex Sharpshell home page sharpshell.codeplex.com. Although there is also the latest reliable version on NuGet, CodePlex can have a written betas available, and the version in the above article is basically available.
Step Three: Sharpcontextmenu
Now it's time to start real research, and watch out. We CountLinesExtension
inherit from SharpContextMenu
:
/// <summary> /// The Count Lines Context Menu Extension /// </summary> Public class countlinesextension:sharpcontextmenu{}
Now that we inherit from SharpContextMenu
this parent class, we are going to implement this abstract class. Right-click and SharpContextMenu
Select ' Implement Abstract Class ':
This operation will automatically generate SharpContextMenu
two functions- CanShowMenu
and CreateMenu
:
/// <summary>///The Count Lines Context Menu Extension/// </summary> Public classcountlinesextension:sharpcontextmenu{protected Override BOOLCanshowmenu () {Throw Newnotimplementedexception (); } protected OverrideContextMenuStrip CreateMenu () {Throw Newnotimplementedexception (); }}
By implementing these two functions, we can achieve all the functions we need. Two function functions are described in detail:
Canshowmenu(It seems a bit wrong)
This function determines whether the current file is the one we need to display the extended menu. The selected file type is a SelectedItemPaths
property. We can check to see if the current file type conforms to the required file type. Returns true if the menu needs to be displayed, or false.
CreateMenu
This function implements the main function. We need to return to the WinForms ContextMenuStrip
.
Here are the specific implementations:
protected Override BOOLCanshowmenu () { //We'll always show the menu. return true; } protected OverrideContextMenuStrip CreateMenu () { //Create the menu strip. varmenu =NewContextMenuStrip (); //Create a ' count lines ' item. varItemcountlines =NewToolStripMenuItem {Text ="Count Lines" }; //When We click, we'll call the ' countlines ' function.Itemcountlines.click + = (sender, args) =countlines (); //ADD the item to the context menu. menu. Items.Add (itemcountlines);
//Return to the menu. returnmenu; } Private voidCountlines () { //Builder for the output. varBuilder =NewStringBuilder (); //Go through each file. foreach(varFilePathinchselecteditempaths) { //Count the lines.Builder. Appendline (string. Format ("{0}-{1} Lines", Path.getfilename (FilePath), File.ReadAllLines (FilePath). Length)); } //Show the ouput. MessageBox.Show (builder. ToString ());}
For CanShowMenu
, we often go straight back to true (soon we'll see why we don't need to validate our text files). For CreateMenu
, we set up a display menu with only one option, that is, ' Count Lines ', and realize the function of reading the number of trips.
Countlines This feature is implemented through SelectedItemPaths
and reads each file function, and then summarizes the display in the pop-up window.
Fourth step: Handling COM Registrations
There is not much left to be done now. First we need to add COMVisible
a reference to our class inside.
[ComVisible (true)] Public class Countlinesextension:sharpcontextmenu
Why is it? Because our class doesn't look like it, but he's essentially a COM Server. If you know some base classes, then you can look at the COM interfaces we just implemented, for example, IShellExtInit
IContextMenu
, and ISharpShellServer
. We don't have to know what's going on here, and she has to have this attribute in order to ensure that the system can create our extensions.
Next, we need to give the assembly a strong name. There are many ways to achieve this, but overall, this is the best approach. Now let's right-click the standalone program and select Properties. Then select "Signature". Select Sign the assembly, select New in select Strong Name key file, and enter the new key file name. You can choose whether you want to protect your key file with a password:
In the final step, we need to correlate our extensions to specific file types. This implementation can be achieved by COMServerAssociation
referencing the (from Sharpshell):
[ComVisible (true)] " . txt " )]publicclass Countlinesextension:sharpcontextmenu
What have we done here? We told Sharpshell that when we registered the server, we wanted to associate any class that was related to ". txt". This means that we are not only limited to. TXT at the end of the file, but any of the similar files. The more authoritative argument is that most of the same icons are shared with txt files.
You can use COMServerAssociation
the properties to implement more features, such as you can also work with folders, drivers, location files to implement specific extensions, and so on. In addition, detailed documentation on the COM Server associations is available on Sharpshell CodePlex.
Okay, but so far it's done! We have created a Countlinesextension assembly project that can add a custom menu to the system as a COM server. For the task of registering the COM server and debugging the deployment, we'll discuss it in the next section.
Debugging shell Extensions
This shell extension will be loaded into the computer explorer, and because of the various circuitous ways of loading. NET COM Server, it can be said that getting the debugger into the process and not executing managed code is almost impossible to achieve. There is, of course, a way to quickly implement debugging. The sharp shell has some tools that make it easier to implement COM server, one of which is called Server Manager. We can use this work to implement debugging.
Open the Server Manager tool, then click File, select Load Server, and then load the generated file (DLL file). You can also drag the file directly into the main interface. The details of the selected file are then displayed next to it.
This server Manager is very useful, it can tell you whether the service has been installed and a variety of other information.
If you want to load the Sharpcontextmenu service, select ' Tools ' and then select ' Test Context Menu '.
When you use the ' Test Context Menu ', you will get a test window. Just a basic implementation of Windows Explorer applications. You can test by right-clicking.
Tip: Regardless of whether your comserverassocations has been generated, the test window will be re-created continuously.
Attaching the debugger to the Servermanager process will allow you to debug your context menu and test its functionality without having to register the server in Windows. Here's how the shell looks when you run the Count line context extension menu
Installing and registering shell extensions
There are many ways to install and register shell extensions. In the next section, I'll look at these carefully.
RegAsm
You can implement installation and ancestral shell extensions by regasm this tool. When using RegAsm, the shell is loaded into the registry (the COM server's class ID is placed in the COM Server Class section and is associated with the path of the actual server file), and the association is also created.
Server Manager
During the development process, the Server Management tool is my preferred method of installing/uninstalling and registering/unregistering, as it allows installation and registration to be handled as a separate step. It will also let you specify whether you are installing/uninstalling in 32-bit or 64-bit mode.
Manual Registry Operations
Generally a bad approach and if you absolutely has to then the MSDN documentation for Shell Extensions describes the CHA Nges that must is made to the registry to manually register a COM server, or a Managed COM server (this sentence will not translate). This document was placed in the next section.
Useful information
- Create a shortcut menu handler in Windows: This is the most important material: details about how the Shell menu extension works in Windows.
- Sharpshell on CodePlex: A dedicated homepage for the Sharpshell project: it includes a variety of literature, discussions, and the latest code research resources and the latest version.
Postscript
Gradually through the use of Sharpshell and. NET to achieve more shell extension functions, to form a complete series. Now that I am implementing the icon handler (which is writing the document), the problem with the property sheet handler has been implemented (and some bugs are being resolved).
[Translate].net shell Extensions-shell context Menus---. NET Shell Extension Right-click menu