使用Windows.Devices.WiFiDirect实现微软显示适配器自动连接问题排查
问题根因
你当前的方案失败的核心原因是微软无线显示器采用Miracast标准实现投屏,你直接通过WiFiDirect建立底层链路后裸连50001端口的方式不符合协议要求:Miracast在链路层建立后,还需要完成WFD服务发现、设备能力协商、RTSP握手、可选的DRM校验等流程,设备才会响应数据传输请求,你的裸连请求没有完成上述协议流程,自然会被设备拒绝或者无响应。
解决方案
不要自行实现底层WiFiDirect连接逻辑,Windows提供了官方的投屏能力入口,直接使用Windows.Media.Casting命名空间下的API即可实现自动投屏到无线显示器,无需处理底层协议细节。参考实现代码如下:
using Windows.Media.Casting; using Windows.Devices.Enumeration; using Windows.UI.ViewManagement; public async Task CastToMicrosoftDisplayAdapter() { string prefix = "MicrosoftDisplayAdapter"; // 查找所有可用的视频投屏设备 string selector = CastingDevice.GetDeviceSelector(CastingPlaybackTypes.Video); DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector); foreach (var devInfo in devices) { if (devInfo.Name.StartsWith(prefix)) { CastingDevice castingDev = await CastingDevice.FromIdAsync(devInfo.Id); CastingRequest request = castingDev.CreateCastingRequest(CastingPlaybackTypes.Video); // 示例为投屏当前应用窗口,若需要投屏整个桌面可搭配Windows.Graphics.Capture API获取捕获源传入 request.Source = ApplicationView.GetForCurrentView().GetCastingSource(); CastingRequestResult result = await request.StartCastingAsync(); if (result.Status == CastingRequestStatus.Succeeded) { // 投屏成功逻辑 return; } } } }
注意事项
- 桌面项目(WPF/WinForms)需要先安装
Microsoft.Windows.SDK.ContractsNuGet包来调用Windows Runtime API,UWP项目可直接调用。 - 首次调用时系统会弹出权限申请提示,同意后后续可以静默调用。
内容的提问来源于stack exchange,提问作者Riko
相关产品推荐
相关产品推荐

