开发者

Call COM wituout COM interop dll

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);
shor开发者_JS百科tcut.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?


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);


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


Ok, since ILMerge is unnaceptable for some reason.

C# includes the ability to interract with underlying COM and Windows DLLs. You could write your own COM interop within the EXE.

Here is an article describing how you can do this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜