C#设置默认打印机
开发中经常会遇到需要用到打印机的问题,那么我们现在来一个Demo修改系统默认打印机。先看运行效果吧。(主要为了展示代码和功能,界面就随便拖拉了一个,比较丑,不要介意。)
界面构建非常简单,首先新建一个Form窗体,拉一个comboBox控件和一个Button然后就可以了。
接下来我们看下代码。
首先是加载本地打印机的类LocalPrinter
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing.Printing; namespace WindowsFormsApplication1 { public class LocalPrinter { private static PrintDocument fPrintDocument = new PrintDocument(); //获取本机默认打印机名称 public static String DefaultPrinter() { return fPrintDocument.PrinterSettings.PrinterName; } public static List<String> GetLocalPrinters() { List<String> fPrinters = new List<String>(); fPrinters.Add(DefaultPrinter()); //默认打印机始终出现在列表的第一项 foreach (String fPrinterName in PrinterSettings.InstalledPrinters) { if (!fPrinters.Contains(fPrinterName)) { fPrinters.Add(fPrinterName); } } return fPrinters; } } }
然后是调用windows 打印机操作api的类Externs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; //必须引入这个命名空间 namespace WindowsFormsApplication1 { public class Externs { [DllImport("winspool.drv")] public static extern bool SetDefaultPrinter(String Name); //调用win api将指定名称的打印机设置为默认打印机 } }
然后就是窗体的Form的代码了,其实就是一个按钮点击事件和初始化的操作
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); InitprinterComboBox(); //加载数据 } /// <summary> /// 初始化ComboBox数据 /// </summary> private void InitprinterComboBox() { List<String> list = LocalPrinter.GetLocalPrinters(); //获得系统中的打印机列表 foreach (String s in list) { printerComboBox.Items.Add(s); //将打印机名称添加到下拉框中 } } private void button1_Click(object sender, EventArgs e) { if (printerComboBox.SelectedItem != null) //判断是否有选中值 { if (Externs.SetDefaultPrinter(printerComboBox.SelectedItem.ToString())) //设置默认打印机 { MessageBox.Show(printerComboBox.SelectedItem.ToString() + "设置为默认打印机成功!"); } else { MessageBox.Show(printerComboBox.SelectedItem.ToString() + "设置为默认打印机失败!"); } } } } }
这样,运行就可以设置默认打印机了。
那么,如何测试是否成功呢?很简单,打开控制面板,在打开打印机的界面,然后运行程序,设置默认打印机,看看是否会改变即可。笔者测试的结果是可以得,但是如果电脑本身没有设置默认打印机,那么设置也会成功,但是那个绿色的默认钩没有显示出来。这时候可以手动设置一下默认,然后再 通过软件修改就会显示那个绿色的默认钩了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现