C# winForm 修改默认打印机(效果不太好,每次修改都会有一个系统的打印弹窗(win10))

时间:2024-02-25 09:37:48

1.界面:1个按钮+1个combobox;

2.开头阴影

using System.Runtime.InteropServices;

3.代码

        private void Form1_Load(object sender, EventArgs e)
        {
            InitprinterComboBox(); //初始化打印机下拉列表选项
        } 
        private void InitprinterComboBox()
        {// 初始化打印机列表
            PrintDocument printDocument = new PrintDocument();
            string defaultPrinter = printDocument.PrinterSettings.PrinterName;//获取默认打印机名

            foreach (string printer in PrinterSettings.InstalledPrinters)
            {//获取所有打印机名称
                combobox1.Items.Add(printer);
                if (printer == defaultPrinter)
                {//默认打印机设置在列表的第一项
                    combobox1.SelectedIndex = combobox1.Items.IndexOf(printer);
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {//设置默认打印机按钮
            try
            {
                if (Externs.SetDefaultPrinter(cmbPrinter.SelectedItem.ToString())) 
                {//设置默认打印机
                    MessageBox.Show(cmbPrinter.SelectedItem.ToString() + "设置为默认打印机成功!");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("设置为默认打印机失败: "+ex.Message);
            }
        }
        class Externs
        {//调用win api将指定名称的打印机设置为默认打印机
            [DllImport("winspool.drv")]//引入
            public static extern bool SetDefaultPrinter(String printerName);//定义外部库函数
        }