You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

迁移WPF到WinUI3:求替代LocalPrintServer与PrintQueue的打印机操作类

替代方案:枚举打印机与获取默认打印机

方案1:使用WinRT原生API(推荐)

WinUI 3基于Windows Runtime,可通过Windows.Devices.Enumeration和Windows.Graphics.Printing命名空间的API实现需求:

枚举所有打印机

通过DeviceInformation.FindAllAsync查询打印机设备,利用设备类ID筛选:

using Windows.Devices.Enumeration;

// 枚举所有打印机
var printerSelector = DeviceClass.Printer;
var devices = await DeviceInformation.FindAllAsync(printerSelector);

foreach (var device in devices)
{
    string printerName = device.Name;
    string deviceId = device.Id; // 可用于后续打印操作
}

获取默认打印机

调用PrintManager的GetDefaultPrintQueueAsync方法:

using Windows.Graphics.Printing;

// 获取默认打印机
var defaultQueue = await PrintManager.GetDefaultPrintQueueAsync();
if (defaultQueue != null)
{
    string defaultPrinterName = defaultQueue.Name;
    string defaultPrinterId = defaultQueue.Id;
}

方案2:兼容System.Printing(仅限非打包应用)

若你的WinUI 3应用为非打包桌面应用(未使用MSIX打包),可直接引用System.Printing.dll,沿用WPF的原有逻辑:

  1. 在项目中添加对System.Printing的引用
  2. 使用以下代码:
using System.Printing;

// 枚举所有打印机
var localPrintServer = new LocalPrintServer();
var printQueues = localPrintServer.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections });

foreach (var queue in printQueues)
{
    string printerName = queue.Name;
}

// 获取默认打印机
var defaultQueue = localPrintServer.DefaultPrintQueue;
string defaultPrinterName = defaultQueue.Name;

注意:该方式在MSIX打包应用中可能触发权限问题,不推荐用于打包场景。

方案3:结合PrintDocument实现轻量需求

若已在使用System.Drawing.Printing.PrintDocument,可通过PrinterSettings类完成枚举与默认打印机获取:

using System.Drawing.Printing;

// 枚举所有已安装打印机
foreach (string printerName in PrinterSettings.InstalledPrinters)
{
    // 处理打印机名称
}

// 获取默认打印机
var printerSettings = new PrinterSettings();
string defaultPrinterName = printerSettings.PrinterName;

此方式仅能获取打印机名称,适合无需额外设备信息的简单场景。

内容的提问来源于stack exchange,提问作者BitKFu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 10:02:35