Have a context menu entry pass parameters to a windows service while it is running
I have a simple windows service called lets say "MyService", built using WCF that on start adds a registry entry to "HKEY_CLASSES_ROOT\Folder\Shell\{ContextMenuEntryName}" thus allowing for the right click menu anywhere in windows to have an entry named : {ContextMenuEntryName}. The target executed on clicking this entry is another program e.g. "{Path}\serviceclient.exe %1". The "%1" gives me the path of the windows folder that that context menu has been invoked on. This program then takes that value and passes it to my service by creating a proxy of the service and invoking its method.
The WindowsService code for its OnStart method is as follows:
protected override void OnStart(string[] args)
{
if (_serviceHost != null)
{
_serviceHost.Close();
}
// Add registry entry for cont开发者_StackOverflow中文版ext menu option System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
string contextMenuCommandPath =
Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.IndexOf("MyService")) +
"serviceclient\\bin\\Debug\\serviceclient.exe %1";
_contextMenu.AddContextMenu(ContextMenuName, contextMenuCommandPath, "Folder");
_contextMenu.AddContextMenu(ContextMenuName, contextMenuCommandPath, "*");
// Create a ServiceHost for the CalculatorService type and
// provide the base address.
_serviceHost = new ServiceHost(typeof(MyService));
// Open the ServiceHostBase to create listeners and start
// listening for messages.
_serviceHost.Open();
}
The serviceclient.exe has the following code after adding a service reference named "MyService" to it:
// Instantiate service proxy
var myServiceClient = new MyService.MyServiceClient();
// Execute monitor target based on path specified (or default).
myServiceClient .Monitor(args.Length > 0 ? args[0] : string.Empty);
I would like to directly pass arguments to the Windows service itself when I click on the context menu entry instead of invoking another separate program that does the same thing.
Would it be possible to have the context menu entry directly pass information to a Windows Service in WCF while it is running?
It doesn't look like it on first glance, but it's a complicated subject. See Creating Shortcut Menu Handlers.
If you implemented a named pipe server inside your Windows service maybe you could send the file path data directly from the context menu command with something like:
echo %1 > \\.\pipe\{pipe-name}
However, you can't use the standard WCF NetNamedPipeBinding to implement the pipe server, because of all the .NET-specific protocol requirements baked into that binding, so you would need to do it either using the System.IO.Pipes
classes, or write a custom WCF transport which just receives raw messages from the pipe.
精彩评论