成功了,做了一个MD与Docx互转的动作:https://getquicker.net/Sharedaction?code=c1e4f757-e2b8-4791-00da-08de76672e1f
请教如何实现选中文件调用动作,而不必打开动作后选择路径
private (string path, int count) GetExplorerSelectionInfo(IntPtr specificHandle = default)
{
try
// 1. 获取当前前台窗口句柄
IntPtr handle = specificHandle == default ? GetForegroundWindow() : specificHandle;
// 2. 通过 COM 组件获取 Shell.Application 对象
Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
dynamic shell = Activator.CreateInstance(shellAppType);
// 3. 遍历所有打开的资源管理器窗口(包括桌面)
foreach (dynamic window in shell.Windows())
// 4. 匹配窗口句柄或判断是否为桌面选中
if (window.HWND == (int)handle || IsDesktopSelected(handle, window))
// 5. 获取窗口中当前选中的项目集合
dynamic items = window.Document.SelectedItems();
// 6. 如果有选中项,返回第一个项的路径和总选中数量
if (items.Count > 0) return (items.Item(0).Path, items.Count);
}
catch { }
return (null, 0);
关键步骤解析:
shell.Windows(): 这一步会列出系统中所有由 explorer.exe 管理的窗口,包括文件夹窗口和系统桌面。
window.HWND == (int)handle: 这里的 handle 是通过 Win32 API GetForegroundWindow() 获取的。代码通过比对句柄,确保只从用户当前正在操作的那个窗口中提取信息。
window.Document.SelectedItems(): 这是最核心的一行。它调用了 Windows Shell 的自动化接口,直接获取当前窗口中被蓝框选中的文件或文件夹对象。
items.Item(0).Path: 获取选中列表中第一个文件的完整路径(String)。
触发位置
这段代码在键盘钩子回调 HookCallback 中被调用。当你按下 空格键 时,程序会先运行这个方法来检测你是否选中了文件,如果拿到了路径,才会弹出预览窗口。
你不懂的就发给AI
private (string path, int count) GetExplorerSelectionInfo(IntPtr specificHandle = default)
{
try
{
// 1. 获取当前前台窗口句柄
IntPtr handle = specificHandle == default ? GetForegroundWindow() : specificHandle;
// 2. 通过 COM 组件获取 Shell.Application 对象
Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
dynamic shell = Activator.CreateInstance(shellAppType);
// 3. 遍历所有打开的资源管理器窗口(包括桌面)
foreach (dynamic window in shell.Windows())
{
// 4. 匹配窗口句柄或判断是否为桌面选中
if (window.HWND == (int)handle || IsDesktopSelected(handle, window))
{
// 5. 获取窗口中当前选中的项目集合
dynamic items = window.Document.SelectedItems();
// 6. 如果有选中项,返回第一个项的路径和总选中数量
if (items.Count > 0) return (items.Item(0).Path, items.Count);
}
}
}
catch { }
return (null, 0);
}
关键步骤解析:
shell.Windows(): 这一步会列出系统中所有由 explorer.exe 管理的窗口,包括文件夹窗口和系统桌面。
window.HWND == (int)handle: 这里的 handle 是通过 Win32 API GetForegroundWindow() 获取的。代码通过比对句柄,确保只从用户当前正在操作的那个窗口中提取信息。
window.Document.SelectedItems(): 这是最核心的一行。它调用了 Windows Shell 的自动化接口,直接获取当前窗口中被蓝框选中的文件或文件夹对象。
items.Item(0).Path: 获取选中列表中第一个文件的完整路径(String)。
触发位置
这段代码在键盘钩子回调 HookCallback 中被调用。当你按下 空格键 时,程序会先运行这个方法来检测你是否选中了文件,如果拿到了路径,才会弹出预览窗口。
你不懂的就发给AI