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

.NET Maui(Windows平台)获取已安装打印机列表问题求助

.NET Maui获取Windows已安装打印机列表问题及解决

我在开发面向Windows平台的.NET Maui应用时,尝试获取已安装打印机列表,过程中遇到了一系列问题,最终找到了解决方案:

初始尝试代码

最初编写的代码如下:

using System.Drawing.Printing;
namespace MauiApp2;
public partial class MainPage : ContentPage
{
    int count = 0;
    public MainPage()
    {
        InitializeComponent();
    }
    private void OnCounterClicked(object sender, EventArgs e)
    {
        la.Text = PrinterSettings.InstalledPrinters.Count.ToString();
    }
} 

添加System.Drawing.Common引用

为了使用PrinterSettings,我在项目中手动添加了引用:

<ItemGroup>
  <Reference Include="System.Drawing.Common">
    <HintPath>C:\Program Files (x86)\dotnet\shared\Microsoft.WindowsDesktop.App\6.0.13\System.Drawing.Common.dll</HintPath>
  </Reference>
</ItemGroup>

但调用PrinterSettings.InstalledPrinters仍未成功获取打印机列表。

修改代码后依然崩溃

之后我将代码修改为仅在Windows平台编译执行:

#if WINDOWS
    public string GetPrinterNames()
    {
        string x = string.Empty;
        try
        {
            x= PrinterSettings.InstalledPrinters.Count.ToString();
        }
        catch(Exception ex) 
        {
            Console.WriteLine(ex.ToString());
        }
        finally
        {
           
        }
        return x;
    }
#endif

应用依然崩溃,触发app.g.i.cs文件中的未处理异常断点:

#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
        UnhandledException += (sender, e) =>
        {
            if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
        };
#endif

最终解决方案

经过排查发现,System.Drawing.Printing在面向.NET 7的.NET Maui中不被支持,将项目切换至.NET 6后,原本的方案即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:11:14