如何点击Windows桌面Widget启动自定义可执行程序?
实现Windows Widget点击启动EXE的方法
步骤1:修改Adaptive Card模板,添加启动按钮
在现有计数器Widget的actions数组中,新增一个Action.Execute按钮,用于触发启动EXE的操作:
const std::string countWidgetTemplate = R"( { "type": "AdaptiveCard", "body": [ { "type": "TextBlock", "text": "You have clicked the button ${count} times" }, { "text":"Rendering Only if Medium", "type":"TextBlock", "$when":"${$host.widgetSize==\"medium\"}" } ], "actions": [ { "type": "Action.Execute", "title": "Increment", "verb": "inc" }, { "type": "Action.Execute", "title": "启动我的程序", "verb": "launch_exe" } ], "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", "version": "1.5" })";
步骤2:修改OnActionInvoked方法,处理启动逻辑
在OnActionInvoked中新增对launch_exe动词的判断,调用Win32 API启动指定的可执行文件:
#include <shellapi.h> // 需要包含此头文件 void WidgetProvider::OnActionInvoked(winrt::WidgetActionInvokedArgs actionInvokedArgs) { auto verb = actionInvokedArgs.Verb(); if (verb == L"inc") { auto widgetId = actionInvokedArgs.WidgetContext().Id(); if (const auto iter = RunningWidgets.find(widgetId); iter != RunningWidgets.end()) { auto& localWidgetInfo = iter->second; // Increment the count localWidgetInfo.customState++; UpdateWidget(localWidgetInfo); } } else if (verb == L"launch_exe") { // 替换为你的可执行文件的绝对路径 const wchar_t* exeAbsolutePath = L"C:\\Your\\Program\\Path\\YourApp.exe"; // 使用ShellExecuteW启动程序,SW_SHOWNORMAL表示正常窗口显示 ShellExecuteW( nullptr, // 父窗口句柄,这里设为nullptr L"open", // 操作类型,"open"表示打开文件/程序 exeAbsolutePath, // 要启动的EXE路径 nullptr, // 命令行参数,无则设为nullptr nullptr, // 工作目录,无则设为nullptr SW_SHOWNORMAL // 窗口显示方式 ); } }
注意事项
- 确保EXE路径是绝对路径,避免因工作目录问题导致启动失败。
- 项目需要链接
shell32.lib:在Visual Studio中,可通过项目属性 -> 链接器 -> 输入 -> 附加依赖项,添加shell32.lib。 - 如果需要传递命令行参数,可将
ShellExecuteW的第四个参数设为对应的参数字符串(例如L"-arg1 value1")。
内容的提问来源于stack exchange,提问作者Vipul Gupta
相关产品推荐
相关产品推荐

