我正在开发需要发送桌面操作快捷方式的应用程序.我发现只有一种方法可以实现它:
var shell = new IWshRuntimeLibrary.WshShell();
var shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(linkFileName);
shortcut.TargetPath = Application.ExecutablePath;
shortcut.WorkingDirectory = Application.StartupPath;
shortcut.Save();
Run Code Online (Sandbox Code Playgroud)
它正在运行coreect,但需要Interop.IWshRuntimeLibrary.dll.我的应用程序需要通过一个小的exe文件进行部署,我不能将任何其他文件包含在包中.
在没有interop dll的情况下调用COM的方法是什么?
shf*_*301 16
是的,您可以在没有互操作库的情况下在.NET中创建COM对象.只要它们的COM对象实现了IDispatch(WScript.Shell可以实现),您就可以轻松地在其上调用方法和属性.
如果您使用的是.NET 4,则动态类型使这很容易.如果没有,你将不得不使用反射来调用方法,这将起作用但不是很漂亮.
.NET 4具有动态性
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();
Run Code Online (Sandbox Code Playgroud)
带有Reflection的.NET 3.5或更早版本
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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3691 次 |
最近记录: |