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

如何在C# WinForms中跳过打印对话框实现直接打印?

解决打印时跳过对话框直接使用默认打印机的问题

你的代码中调用PrintDocument.Print()时会弹出打印对话框,原因是未指定具体打印机,系统会自动弹出选择窗口。要实现直接用默认打印机打印,只需修改打印相关代码部分,具体如下:

修改后的完整代码

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        conn.Open();
        string query = "INSERT INTO bank_check_kassa OUTPUT INSERTED.formatted_id default values";
        SqlCommand command = new SqlCommand(query, conn);
        string insertedID = (string)command.ExecuteScalar();
        label1.Padding = new Padding(-50, 0, 0, 0);
        label1.Text = "Novbedeki siraniz " + insertedID.ToString();

        // Printer ayarları
        using (PrintDocument pd = new PrintDocument())
        {
            // 设置为系统默认打印机
            pd.PrinterSettings.PrinterName = PrinterSettings.InstalledPrinters.Cast<string>()
                .FirstOrDefault(p => new PrinterSettings { PrinterName = p }.IsDefaultPrinter);
            
            // 绑定打印内容事件
            pd.PrintPage += (s, args) => ProvideContent1(s, args, insertedID);
            // 直接打印,不再弹出对话框
            pd.Print();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error " + ex);
    }
    finally
    {
        conn.Close();
    }
}

private void ProvideContent1(object sender, PrintPageEventArgs e, string insertedID)
{
    // 使用using包裹Font和Brush,避免资源泄漏
    using (Font font = new Font("Arial", 12, FontStyle.Regular))
    using (SolidBrush brush = new SolidBrush(Color.Black))
    {
        float x = 100;
        float y = 100;
        e.Graphics.DrawString("Novbedeki siraniz: " + insertedID, font, brush, x, y);
    }
}

关键修改说明

  • 指定默认打印机:通过遍历PrinterSettings.InstalledPrinters找到系统默认打印机,将其名称赋值给pd.PrinterSettings.PrinterName,系统便会直接使用该打印机,不再弹出选择对话框。
  • 优化资源管理:在ProvideContent1方法中用using语句包裹Font和SolidBrush,确保非托管资源及时释放,避免内存泄漏。

如果项目已引用System.Printing程序集,也可以用更简洁的方式获取默认打印机名称:

pd.PrinterSettings.PrinterName = PrintQueue.DefaultPrintQueue.Name;

内容的提问来源于stack exchange,提问作者Мачо Мино

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:34:59