c# - 使用 Windows.Devices.WiFiDirect 与 Microsoft 显示适配器自动连接
问题描述
首先,我已经广泛阅读了 Windows 10 上自动连接到 MS 无线显示器的内容,并且基本上尝试了所有解决方案。(从技术上讲,我确实让 AutoHotKey 解决方案工作了,实际上甚至在研究之前就这样做了。但是,我觉得这有点不专业,而且肯定有一些 API 可以连接到这个东西。)在经历了所有这些之后,我刚刚开始阅读不同的命名空间。最后,我找到了 Windows.Devices.WiFiDirect。这给了我最大的进步,即它开始连接并在屏幕上显示,然后出现异常,指出设备无法访问。很气人。
谁能准确解释这里发生了什么?似乎这应该是将我的屏幕连接到此设备的正确方法,但它只是无法正常工作。下面的代码,它非常简短明了。
编辑:
根据 Roy Li 的建议,我尝试使用不同的 socket.ConnectAsync 方法重载。这实际上确实产生了影响,但我仍然收到一个例外,尽管是一个不同的例外。该方法现在尝试连接更长时间但仍然失败,这次出现“连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,因为连接的主机没有响应”异常。这是否意味着 Window 的操作系统在连接到此设备时正在使用某种秘密握手?如果是这样,这可能是一个死胡同。代码已在下面更新。
static async Task Main()
{
string id = null;
string prefix = "MicrosoftDisplayAdapter";
WiFiDirectDevice device;
StreamSocket socket = new StreamSocket();
try
{
DeviceInformationCollection devInfoCollection = await DeviceInformation.FindAllAsync(WiFiDirectDevice.GetDeviceSelector());
foreach (DeviceInformation devInfo in devInfoCollection)
{
if (devInfo.Name.StartsWith(prefix))
{
id = devInfo.Id;
}
}
device = await WiFiDirectDevice.FromIdAsync(id);
var endpointPairCollection = device.GetConnectionEndpointPairs();
await socket.ConnectAsync(endpointPairCollection[0].RemoteHostName, "50001"); //This line begins connecting to the display but ultimately fails
}
catch (Exception e)
{
//device unreachable exception
}
}
解决方案
我终于找到了符合我需要的东西。我遇到了https://social.msdn.microsoft.com/Forums/en-US/7608d127-d864-436a-802e-472fd55cc02c/use-projectionmanager-from-net-framework?forum=csharpgeneral,这给了我一个方法投射/投影到 Microsoft 显示适配器。正如链接所述,我确实得到了一个“灾难性错误”,但它确实建立了连接并保持它,无论如何。我的代码最终如下所示:
static async Task Main()
{
string prefix = "MicrosoftDisplayAdapter";
DeviceInformation displayAdapter = null;
try
{
//Get projection devices
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(ProjectionManager.GetDeviceSelector());
foreach (DeviceInformation device in devices)
{
if (device.Name.StartsWith(prefix))
{
displayAdapter = device;
}
}
//Start projection. This throws an error but works without issue.
await ProjectionManager.StartProjectingAsync(0, 0, displayAdapter);
}
catch (Exception e)
{
//Ignore this error
if (e.Message.StartsWith("Catastrophic"))
{
//Change display to use secondary only
Process proc = new Process();
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = @"C:\Windows\Sysnative\DisplaySwitch.exe";
proc.StartInfo.Arguments = "/external";
proc.Start();
proc.WaitForExit();
}
else
{
Console.WriteLine(e);
}
}
}
推荐阅读
- android - 假设这个世界上的所有 Android 设备都使用“\n”作为行分隔符是否可以?
- javascript - 为每个创建的元素创建一个新的 onclick 函数
- yum - download.postgresql.org 的证书已过期
- node.js - 错误:听 EADDRNOTAVAIL 13.*.*.*:3004
- kubernetes - 如何在 envoyproxy 中配置公共访问 web api?
- flutter - Flutter - resizeToAvoidBottomInset 属性使我的 ListView 被键盘覆盖
- xml - 这两个 XML 数组片段之间有什么区别吗?
- tensorflow - 如何解释 tensorflow.keras.preprocessing.image_dataset_from_directory 文档?
- rust - 如何将结构与字符串成员匹配
- wordpress - 在 WooCommerce 档案页面上添加带有产品类别 ID 的额外类