问题描述
我有一个 C# 应用程序,它创建快捷方式来启动具有特定参数和初始目录的其他程序.我希望用户能够从 Windows 窗体中拖动快捷方式并将其拖放到任何相关的位置,例如桌面、开始菜单等,但我真的不知道如何处理,谁能指出我方向对吗?
I have a C# application that creates shortcuts to launch other programs with specific arguments and initial directories. I would like the user to be able to drag a shortcut from the Windows form and drop it anywhere relevant like the desktop, the start menu, and so on but I don't really know how to handle that, could anyone point me in the right direction?
我见过一些使用 PInvoke 和 IShellLink 的示例 喜欢 这个,或阅读像 这里,它已经帮助创建快捷方式并将它们保存在 .lnk 文件中.我假设当用户启动拖动操作时,我必须在 DoDragDrop()
调用中交出数据,例如通过处理 MouseDown
信号.据我所知,我想我需要确切地知道目标期望接受丢弃的类型,以及如何序列化快捷方式,但找不到关于该部分的任何信息.
I have seen a few samples using PInvoke and IShellLink like this one, or read answers on SO like here, which already help create shortcuts and save them in a .lnk file. I assume I have to hand over data in a DoDragDrop()
call when the user initiates a drag operation, for example by handling a MouseDown
signal. That's as far as I got, I suppose I need to know exactly which type the target is expecting to accept the drop, and how to serialize the shortcut, but couldn't find any information on that part.
也许另一种选择是获取放置的位置,并从我的应用程序中管理它,但我还是有点不知道如何做到这一点.
Perhaps another option would be to get the location of the drop, and manage that from my application, but there again I'm a bit clueless as how to do that.
框架版本目前是3.5,我只考虑Windows平台.
The framework version is currently 3.5, and I'm only considering Windows platforms.
提前感谢您的帮助!
更新/解决方案:
使用上述ShellLink 代码创建一个临时快捷方式文件,我只是使用 DataObject
进行拖放,如下例所示:
Using the ShellLink code mentioned above to create a temporary shortcut file, I simply used DataObject
for the drag and drop, like in the following example:
private void picShortcut_MouseDown(object sender, MouseEventArgs e)
{
ShellLink link = new ShellLink();
// Creates the shortcut:
link.Target = txtTarget.Text;
link.Arguments = txtArguments.Text;
link.Description = txtDescription.Text;
link.IconPath = txtIconFile.Text;
link.IconIndex = (txtIconIndex.Text.Length > 0 ?
System.Int32.Parse(txtIconIndex.Text) : 0);
link.Save("tmp.lnk");
// Starts the drag-and-drop operation:
DataObject shortcut = new DataObject();
StringCollection files = new StringCollection();
files.Add(Path.GetFullPath("tmp.lnk"));
shortcut.SetFileDropList(files);
picShortcut.DoDragDrop(shortcut, DragDropEffects.Copy);
}
如果您考虑 PInvoke 代码(此处未显示),则相当复杂,我仍然需要使用目标名称创建这个临时文件.如果有人知道...呃,捷径,欢迎!也许通过移植 John Knoeller 给出的代码一个链接(谢谢!).
Quite complicated if you consider the PInvoke code (not shown here), and I still need to create this temporary file with the target name. If anyone knows a... erm, shortcut, it's welcome! Perhaps by porting the code for which John Knoeller gave a link (thanks!).
推荐答案
Raymond Chen 在他的博客上写了一篇关于这个主题的整篇文章,查看 拖动一个虚拟文件
Raymond Chen did a whole article on this very topic on his blog check out dragging a virtual file
这篇关于拖动&删除动态创建的快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!