4

.NET 6学习笔记(4)——如何在.NET 6的Desktop App中使用Windows Runtime API - 楼上那...

 1 year ago
source link: https://www.cnblogs.com/manupstairs/p/16818903.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

.NET 6学习笔记(4)——如何在.NET 6的Desktop App中使用Windows Runtime API

Windows Runtime API是当初某软为了区别Win32 API,力挺UWP而创建的另一套Windows 10专用的API集合。后来因为一些原因,UWP没火。为了不埋没很有价值的Windows Runtime API,某软只好允许.NET Framework的程序调用Windows Runtime API,我们在《迁移桌面程序到MS Store(4)——桌面程序调用Win10 API》中讨论过。
而从.NET 5开始,新.NET中Desktop App调用WinRT runtime的方式又发生了变化。总体来说更简单了,今天我们就一起来实践一番。
首先我们创建一个新的Console工程。Framework选择.NET 6。除了学习性质的个人项目,否则我只推荐Long-term support的版本,商业性质的项目发布出去以后,突然对应版本的.NET Runtime官方支持周期到了,是比较滑稽的。

362529-20221023165530362-97750493.png

在这样一个Console的程序中,我打算访问一个常见的WinRT API:Windows.Devices.Raidos命名空间下的Radio类。当然我们也可以通过Win32 API去操作蓝牙,可如果仅希望开、关和查询蓝牙状态这样的简单操作,Win32 API就显得有些蛋疼了。

而Radio类对.NET 程序而言,就显得友好许多。首先让我们右键编辑project文件。

362529-20221023165558122-372222579.png

 将默认的:

<TargetFramework>net6.0</TargetFramework>

更改为对应具体Windows SDK版本:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0-windows10.0.22000.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

其中SDK版本的对应关系如下:
• net6.0-windows10.0.17763.0: 对应 Windows 10, version 1809.
• net6.0-windows10.0.18362.0: 对应 Windows 10, version 1903.
• net6.0-windows10.0.19041.0: 对应 Windows 10, version 2004.
• net6.0-windows10.0.22000.0: 对应 Windows 11.
完成这一步之后,即可像UWP程序里一样,通过using添Windows.Devices.Raidos命名空间,来直接使用WinRT API了。

using Windows.Devices.Radios;

// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");


foreach (var radio in await Radio.GetRadiosAsync())
{
    Console.WriteLine($"Name:{radio.Name}, Kind:{radio.Kind}, State:{radio.State}");
}

Console.ReadLine();

是不是又一次觉得啊软这回能Make desktop great again!这个现在还不好说,但学习一下如何开发现代化的Desktop App总不是坏事。

附上Github链接:

manupstairs/WinRTApiInNet6: Introduce how to use WinRT API in .NET 6 project. (github.com)

以下链接,是MS Learn上Windows开发的入门课程,单个课程三十分钟到60分钟不等,想要补充基础知识的同学点这里:

开始使用 Visual Studio 开发 Windows 10 应用

开发 Windows 10 应用程序

编写首个 Windows 10 应用

创建 Windows 10 应用的用户界面 (UI)

增强 Windows 10 应用的用户界面

在 Windows 10 应用中实现数据绑定


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK