Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call COM wituout COM interop dll

Tags:

c#

com

I'm developing application that require send shortcut to desktop operation. I found only one way to implement it:

var shell = new IWshRuntimeLibrary.WshShell();
var shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(linkFileName);
shortcut.TargetPath = Application.ExecutablePath;
shortcut.WorkingDirectory = Application.StartupPath;
shortcut.Save();

It's working coreect, but Interop.IWshRuntimeLibrary.dll required. My application require deployment throught one small exe file, I can't include any other files into package.

Is where a way to call COM without interop dll?

like image 811
Viacheslav Smityukh Avatar asked Nov 28 '22 10:11

Viacheslav Smityukh


2 Answers

Yes you can create a COM object in .NET without an interop library. As long as they COM object implements IDispatch (which WScript.Shell does) you can call methods and properties on it easily.

If you are using .NET 4, the dynamic type makes this very easy. If not you'll have to use Reflection to call the methods, which will work but isn't nearly as pretty.

.NET 4 with dynamic

Type shellType = Type.GetTypeFromProgID("WScript.Shell");
dynamic shell = Activator.CreateInstance(shellType);
dynamic shortcut = shell.CreateShortcut(linkFileName);
shortcut.TargetPath = Application.ExecutablePath;
shortcut.WorkingDirectory = Application.StartupPath;
shortcut.Save();

.NET 3.5 or earlier with Reflection

Type shellType = Type.GetTypeFromProgID("WScript.Shell");
object shell = Activator.CreateInstance(shellType);
object shortcut = shellType.InvokeMember("CreateShortcut",
      BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,
      null, shell, new object[] { linkFileName });
Type shortcutType = shortcut.GetType();
shortcutType.InvokeMember("TargetPath",
      BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty,
      null, shortcut, new object[] { Application.ExecutablePath });
shortcutType.InvokeMember("WorkingDirectory",
      BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty, 
      null, shortcut, new object[] { Application.StartupPath });
shortcutType.InvokeMember("Save",
      BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,
      null, shortcut, null);
like image 86
shf301 Avatar answered Dec 07 '22 23:12

shf301


You can use a Microsoft utility called ILMerge, downloadable from here, to merge the DLL into your exe.

There is a brief description on how to use it in this article

like image 24
iandotkelly Avatar answered Dec 07 '22 23:12

iandotkelly