using System.Collections.Generic;
using System.Drawing.Printing;
using System.Runtime.InteropServices;

namespace XHWK.WKTool.Utils
{
    class ZPrintUtils
    {
        private static PrintDocument fPrintDocument = new PrintDocument();
        /// <summary>
        /// 获取本机默认打印机名称
        /// </summary>
        /// <returns></returns>
        public static string DefaultPrinter()
        {
            return fPrintDocument.PrinterSettings.PrinterName;
        }

        /// <summary>
        /// 获取打印机列表
        /// </summary>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// 调用win api将指定名称的打印机设置为默认打印机
        /// </summary>
        /// <param name="Name"></param>
        /// <returns></returns>
        [DllImport("winspool.drv")]
        public static extern bool SetDefaultPrinter(string Name);

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="PDFPath">打印文件的路径</param>
        /// <param name="PrinterName">打印机的名称</param>
        public static void Print(string PDFPath, string PrinterName)
        {
            //设置默认打印机
            SetDefaultPrinter(PrinterName);
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            //不能启动进程是否显示错误弹窗，如果文件没有打开方式会提示选择文件的打开方式
            p.StartInfo.ErrorDialog = true;
            //不显示调用程序窗口,但是对于某些应用无效
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            //采用操作系统自动识别的模式
            p.StartInfo.UseShellExecute = true;
            //要打印的文件路径
            p.StartInfo.FileName = PDFPath;
            //指定执行的动作，是打印，即print，打开是 open
            p.StartInfo.Verb = "print";
            //开始打印
            p.Start();
            //等待15秒
            p.WaitForExit(15000);
        }
    }
}
