PowerShell开发Windows 10 Toast通知:回复按钮POST请求未触发
问题分析与修复方案
你的代码主要存在几个关键问题,导致点击回复后数据无法成功发送,以下是具体问题和修复方案:
1. 无效的应用AUMID
$app = '{UUID}\powershell.exe'是错误的应用用户模型ID(AUMID),Windows需要正确的AUMID才能关联Toast通知与激活事件。对于PowerShell,你可以使用默认的AUMID,或者通过命令获取:
# 获取PowerShell的AUMID Get-StartApps | Where-Object Name -match "PowerShell"
替换为正确的值,比如:
$app = "Microsoft.PowerShell"
2. 脚本提前退出,无法捕获激活事件
调用Show($toast)后,脚本会立即执行完毕并退出,此时激活事件的回调函数已经不存在,无法触发POST请求。需要在显示通知后让脚本保持运行:
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("$app").Show($toast) # 保持脚本运行30秒,确保能捕获激活事件 Start-Sleep -Seconds 30
3. 缺少错误处理与调试信息
原代码没有任何错误捕获机制,无法排查POST请求失败的原因。可以添加try-catch块输出调试信息:
$toast.add_Activated({ param($sender, $e) # 先检查用户输入是否存在 if ($e.UserInput.ContainsKey('textBox')) { $reply = $e.UserInput['textBox'] Write-Host "收到回复内容:$reply" try { $uri = "https://your-api-endpoint.com" $body = @{ id = $reply } | ConvertTo-Json $response = Invoke-RestMethod -Uri $uri -Method Post -Body $body -ContentType "application/json" Write-Host "POST请求成功,响应:$($response | ConvertTo-Json -Compress)" } catch { Write-Host "POST请求失败:$($_.Exception.Message)" } } else { Write-Host "未获取到输入内容" } })
修复后的完整代码
Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null # 使用正确的PowerShell AUMID $app = "Microsoft.PowerShell" $template = @" <toast> <visual> <binding template="ToastGeneric"> <text>Hello World</text> <text>This is a simple toast message</text> </binding> </visual> <actions> <input id="textBox" type="text" placeHolderContent="Type a reply" /> <action activationType="foreground" content="Reply" arguments="reply" /> </actions> </toast> "@ $xml = New-Object Windows.Data.Xml.Dom.XmlDocument $xml.LoadXml($template) $toast = [Windows.UI.Notifications.ToastNotification]::new($xml) $toast.add_Activated({ param($sender, $e) if ($e.UserInput.ContainsKey('textBox')) { $reply = $e.UserInput['textBox'] Write-Host "回复内容:$reply" try { $uri = "https://your-api-endpoint.com" $body = @{ id = $reply } | ConvertTo-Json $response = Invoke-RestMethod -Uri $uri -Method Post -Body $body -ContentType "application/json" Write-Host "请求成功:$($response | ConvertTo-Json -Compress)" } catch { Write-Host "请求失败:$($_.Exception.Message)" } } else { Write-Host "无输入内容" } }) [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("$app").Show($toast) # 保持脚本运行,等待激活事件 Start-Sleep -Seconds 30
额外优化建议
- 若需要长期监听Toast事件,可将脚本设为后台进程,或通过任务计划程序触发。
- 敏感API请求建议添加身份验证头,比如
-Headers @{Authorization = "Bearer token"}。 - 可给Toast添加
duration="long"属性,延长通知显示时间:<toast duration="long">
内容的提问来源于stack exchange,提问作者mikey186
相关产品推荐
相关产品推荐

