如何捕获ToastNotificationManager创建的带输入框Toast通知的用户输入
捕获带输入框吐司通知的用户输入的实现方法
实现原理
你当前代码里配置的Send按钮激活类型为
background,用户点击按钮后,输入框内容会和按钮参数一起封装到激活事件的返回值中,你只需要监听对应激活事件即可提取输入内容。
方案1:前台激活捕获(适合PowerShell临时会话场景)
这是最适配你当前场景的方案,修改按钮激活类型为前台,注册通知激活事件即可直接在当前会话拿到输入内容,完整可运行代码如下:
# 调整Toast模板中Send按钮的激活类型为foreground [xml]$ToastTemplate = @" <toast launch="chatLaunchArg"> <visual> <binding template="ToastGeneric"> <text>Emily</text> <text>Coming tonight for the tea party?</text> </binding> </visual> <actions> <input id="idTextBox1" type="text" placeHolderContent="reply" /> <action content="Send" hint-inputId="idTextBox1" activationType="foreground" arguments="argSendPress" /> </actions> </toast> "@ $ToastXml = New-Object Windows.Data.Xml.Dom.XmlDocument $ToastXml.LoadXml($ToastTemplate.OuterXml) $AppID = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe' $Notification = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($AppID) # 实例化Toast通知对象 $toast = New-Object Windows.UI.Notifications.ToastNotification($ToastXml) # 注册激活事件捕获用户输入 Register-ObjectEvent -InputObject $toast -EventName Activated -Action { param($sender, $e) # 按输入框的id提取用户填写的内容 $userInput = $e.UserInput["idTextBox1"] # 此处可自定义对输入内容的处理逻辑,比如打印、存储、调用其他接口 Write-Host "用户输入的回复内容:$userInput" } | Out-Null # 显示通知 $Notification.Show($toast)
方案2:后台激活捕获(适合常驻后台场景)
如果你需要保留activationType="background"的配置,需要额外完成Windows后台任务注册:
- 给你使用的PowerShell AppID注册
ToastNotificationActionTrigger类型的后台触发器 - 在后台任务的执行逻辑中,通过事件参数的
UserInput属性,以输入框ididTextBox1作为key即可提取输入内容
注意事项
- 需确保Windows系统的PowerShell通知权限已开启,否则激活事件不会触发
- 前台方案的事件监听仅在当前PowerShell会话生效,会话关闭后监听自动失效
内容的提问来源于stack exchange,提问作者Dora
相关产品推荐
相关产品推荐

