C#设置与获取默认打印机 获取打印机列表

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FT_Tools
{
    public class Externs
    {
        [DllImport("winspool.drv")]
        public static extern bool SetDefaultPrinter(String Name); //调用win api将指定名称的打印机设置为默认打印机
    }
    public class LocalPrinter
    {
        private static PrintDocument fPrintDocument = new PrintDocument();
        //获取本机默认打印机名称
        public static String DefaultPrinter()
        {
            return fPrintDocument.PrinterSettings.PrinterName;
        }
        public static List GetLocalPrinters()
        {
            List fPrinters = new List();
            fPrinters.Add(DefaultPrinter()); //默认打印机始终出现在列表的第一项
            foreach (String fPrinterName in PrinterSettings.InstalledPrinters)
            {
                if (!fPrinters.Contains(fPrinterName))
                {
                    fPrinters.Add(fPrinterName);
                }
            }
            return fPrinters;
        }
    }
    class CRC32
    {
        private static ulong[] Crc32Table;
        //生成CRC32码表
        private static void GetCRC32Table()
        {
            ulong Crc;
            Crc32Table = new ulong[256];
            int i, j;
            for (i = 0; i < 256; i++)
            {
                Crc = (ulong)i;
                for (j = 8; j > 0; j--)
                {
                    if ((Crc & 1) == 1)
                        Crc = (Crc >> 1) ^ 0xEDB88320;
                    else
                        Crc >>= 1;
                }
                Crc32Table[i] = Crc;
            }
        }
        /// 
        /// 获取字符串的CRC32校验值
        /// 
        /// 十六进制字符串
        /// 32位CRC十六进制字符串
        public static string GetCRC32(string strHex)
        {
            //生成码表
            GetCRC32Table();
            strHex = strHex.Replace(" ", "");
            byte[] buffer = FT_Tools.MySerialPort.hexConvertToByteArray(strHex);
            ulong value = 0xffffffff;
            int len = buffer.Length;
            for (int i = 0; i < len; i++)
            {
                value = (value >> 8) ^ Crc32Table[(value & 0xFF) ^ buffer[i]];
            }
            //return value ^ 0xffffffff;
            return String.Format("{0:X8}", value ^ 0xffffffff);
        }
    }
    class MyAPI
    {
        public delegate void MyDel(string str);//声明一个自定义委托,相当于函数指针
        
        /// 
        /// 获取单元格类型
        /// 
        /// 目标单元格
        /// 
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return null;
                case CellType.Boolean:
                    return cell.BooleanCellValue;
                case CellType.Numeric:
                    return cell.NumericCellValue;
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Error:
                    return cell.ErrorCellValue;
                case CellType.Formula:
                default:
                    return "=" + cell.CellFormula;
            }
        }

        /// 
        /// Excel导入成DataTble 支持xls、xlsx文件 ,过滤表头
        /// 
        /// 导入路径(包含文件名与扩展名)
        /// 
        public static DataTable ExcelToTable(MyDel Log,string file)
        {
            if (!File.Exists(file)){    Log("错误 Excel文件不存在:"+file);  return null; }
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                if (workbook == null) {  Log("workbook为空"); return null; }
                ISheet sheet = workbook.GetSheetAt(0);//第0个表

                //表头  
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List columns = new List();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString())); //默认
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }
        //只支持.xls,不再使用
        public static DataTable GetDataFromExcelByConn(MyDel Log,string filePath, bool hasTitle = false)
        {
            //OpenFileDialog openFile = new OpenFileDialog();
            //openFile.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
            //openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //openFile.Multiselect = false;
            //if (openFile.ShowDialog() == DialogResult.Cancel) return null;
            //var filePath = openFile.FileName;
            if (!File.Exists(filePath))
            {
                Log("错误 Excel文件不存在:"+ filePath);
                return null;
            }
            string fileType = System.IO.Path.GetExtension(filePath);
            if (string.IsNullOrEmpty(fileType)) return null;

            using (DataSet ds = new DataSet())
            {
                string strCon = string.Format("Provider=Microsoft.Jet.OLEDB.{0}.0;" +
                                "Extended Properties=\"Excel {1}.0;HDR={2};IMEX=1;\";" +
                                "data source={3};",
                                (fileType == ".xls" ? 4 : 12), (fileType == ".xls" ? 8 : 12), (hasTitle ? "Yes" : "NO"), filePath);



                using (OleDbConnection myConn = new OleDbConnection(strCon))
                {
                    myConn.Open();
                    DataTable schemaTable = myConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
                    string tableName = schemaTable.Rows[0][2].ToString().Trim();
                    string strCom = " SELECT * FROM [" + tableName + "$]";
                    using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn))
                    {
                        myCommand.Fill(ds);
                    }

                    if (ds == null || ds.Tables.Count <= 0)
                    {
                        Log("Excel表或内容为空");
                        return null;
                    }
                    return ds.Tables[0];
                }
            }
        }
        //创建去扩展名的文件夹
        public static string CreateDirectorybyFileName(string fileName)
        {
            string fileNameWithoutExtenstion = Path.GetFileNameWithoutExtension(fileName);
            string path = AppDomain.CurrentDomain.BaseDirectory;//当前目录
            if (!string.IsNullOrEmpty(path))
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path += fileNameWithoutExtenstion;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            return path+"\\";
        }
        public static bool isExistsAlphabet(string str)
        {
            return Regex.Matches(str, "[a-zA-Z]").Count > 0;
        }
        public static bool checkSN(MyDel Log,TextBox sn)
        {
            sn.Text = sn.Text.ToUpper(); //变大写
            sn.Text = sn.Text.Trim(); //删除前后空白
            int SNLength = Convert.ToInt32(FT_Tools.Program.myIni.ReadString("通用", "SNLength", "15"));
            if (sn.Text.Length != SNLength)
            {
                Log("错误 配置文件中限定SN Length为"+ SNLength + ",当前为:" + sn.Text.Length+" SN:"+ sn.Text);
                sn.Text = "";
                sn.Focus();
                return false;
            }
            if (!isExistsAlphabet(sn.Text)  && !sn.Text.Contains("-"))
            {
                Log("错误 SN应该含有字母或-:" + sn.Text);
                sn.Text = "";
                sn.Focus();
                return false;
            }
            return true;
        }

        //[DllImport("user32.dll")]
        //public static extern int SendMessage(int hWnd, // handle to destination window 
        //uint Msg, // message 
        //int wParam, // first message parameter 
        //int lParam // second message parameter 
        //);
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern int WriteProfileString(string lpszSection, string lpszKeyName, string lpszString);

        [DllImport("gdi32")]
        public static extern int AddFontResource(string lpFileName);
        const int WM_FONTCHANGE = 0x001D;
        const int HWND_BROADCAST = 0xffff;

        public static string InstallFont(MyDel Log, string fontPath)
        {
            try
            {
                string fontFileName = Path.GetFileName(fontPath);
                string fontNameWithoutExtenstion = Path.GetFileNameWithoutExtension(fontPath);
                string WinFontDir = Environment.GetEnvironmentVariable("WINDIR") + "\\Fonts";
                string FontPath = WinFontDir + "\\" + fontFileName;
                Font f = new Font(fontNameWithoutExtenstion, 8, FontStyle.Bold); //测试
                if (!fontNameWithoutExtenstion.Equals(f.FontFamily.Name)) //系统中字体是否存在
                {
                    if (!File.Exists(fontPath)) //路径中字体是否存在
                    {
                        Log("错误 字体文件路径不存在【" + fontPath + "】 请将字体文件复制到C:\\Windows\\Fonts下,再运行");
                        return null;
                    }
                    File.Copy(fontPath, FontPath,true);
                    AddFontResource(FontPath);
                    WriteProfileString("fonts", fontNameWithoutExtenstion + "(TrueType)", fontFileName);
                    //重新打开应用
                    Application.ExitThread();
                    Application.Exit();
                    Application.Restart();
                    Process.GetCurrentProcess().Kill();

                    //f = new Font(fontNameWithoutExtenstion, 8, FontStyle.Bold); //检查一遍
                    //if (!fontNameWithoutExtenstion.Equals(f.FontFamily.Name))
                    //{
                    //    Log("错误 请将字体【" + fontNameWithoutExtenstion + ".ttf】复制到C:\\Windows\\Fonts下,再运行");
                    //    return null;
                    //}
                }             
                return fontNameWithoutExtenstion;
            }
            catch (Exception e)
            {
                Log("请第一次使用管理员运行,以便自动安装字体。"+e.ToString());
            }
            return null;
        }

        /// 
        ///      写入文件
        /// 
        /// 
        /// 文件路径加路径
        /// 
        /// 
        /// 
        /// 
        public static bool WriteToFile(MyDel Log, string path,  string content,bool append=false,bool isBin=false)
        {    
            try
            {
                //string path = AppDomain.CurrentDomain.BaseDirectory;//当前目录
                if (!string.IsNullOrEmpty(path))
                {                  
                    //if (!Directory.Exists(path))
                    //{
                    //    Directory.CreateDirectory(path);
                    //}
                    //path +=  DateTime.Now.ToString("yyyyMMdd");//日期文件夹
                    //if (!Directory.Exists(path))
                    //{
                    //    Directory.CreateDirectory(path);
                    //}
                    //path += "\\"+fileName; //文件名
                    if (!File.Exists(path))
                    {
                        FileStream fs = File.Create(path);
                        fs.Close();
                    }
                    if (File.Exists(path))
                    {
                        if (isBin)
                        {
                            using (FileStream fs = new FileStream(path, append?FileMode.Append: FileMode.Create, FileAccess.Write))
                            {                           
                                byte[] byteArray = FT_Tools.MySerialPort.hexConvertToByteArray(content);
                                fs.Write(byteArray, 0, byteArray.Length);
                            }
                        }
                        else
                        {
                            using (StreamWriter sw = new StreamWriter(path, append, System.Text.Encoding.UTF8)) //System.Text.Encoding.Default
                            {
                                sw.Write(content);
                            }
                        }                        
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                Log("错误 "+e.ToString());
                return false;
            }
            return false;
        }
        /// 
        ///  计算指定文件的MD5值
        /// 
        /// 指定文件的完全限定名称
        /// 返回值的字符串形式
        public static String ComputeMD5(String fileName)
        {
            String hashMD5 = String.Empty;
            //检查文件是否存在,如果文件存在则进行计算,否则返回空值
            if (System.IO.File.Exists(fileName))
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    //计算文件的MD5值
                    System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
                    Byte[] buffer = calculator.ComputeHash(fs);
                    calculator.Clear();
                    //将字节数组转换成十六进制的字符串形式
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < buffer.Length; i++)
                    {
                        stringBuilder.Append(buffer[i].ToString("x2"));
                    }
                    hashMD5 = stringBuilder.ToString();
                }//关闭文件流
            }//结束计算
            return hashMD5;
        }//ComputeMD5

        /// 
        /// 复制文件夹及文件
        /// 
        /// 原文件路径
        /// 目标文件路径
        /// 
        public static int CopyFolder(string sourceFolder, string destFolder)
        {
            try
            {
                //如果目标路径不存在,则创建目标路径
                if (!System.IO.Directory.Exists(destFolder))
                {
                    System.IO.Directory.CreateDirectory(destFolder);
                }
                //得到原文件根目录下的所有文件
                string[] files = System.IO.Directory.GetFiles(sourceFolder);
                foreach (string file in files)
                {
                    string name = System.IO.Path.GetFileName(file);
                    string dest = System.IO.Path.Combine(destFolder, name);
                    System.IO.File.Copy(file, dest,true);//复制文件
                }
                //得到原文件根目录下的所有文件夹
                string[] folders = System.IO.Directory.GetDirectories(sourceFolder);
                foreach (string folder in folders)
                {
                    string name = System.IO.Path.GetFileName(folder);
                    string dest = System.IO.Path.Combine(destFolder, name);
                    CopyFolder(folder, dest);//构建目标路径,递归复制文件
                }
                return 1;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return 0;
            }

        }//copy folder
         /// 
         /// 启动外部.exe应用
         /// 
         /// 
        public static void Exec(string exeName)
        {
            try
            {
                ProcessStartInfo info = new ProcessStartInfo();
                info.FileName = exeName;
                info.Arguments = "";
                info.WindowStyle = ProcessWindowStyle.Normal;
                Process pro = Process.Start(info);
                //pro.WaitForExit();
            }
            catch (System.Exception e)
            {
                MessageBox.Show("错误:" + e.ToString());
            }

        }
        /// 
        /// 结束进程
        /// 
        /// exe的进程名,不是文件名
        public static void killProcess(string processName)
        {
            Process[] allProgresse = System.Diagnostics.Process.GetProcessesByName(processName);
            foreach (Process closeProgress in allProgresse)
            {
                if (closeProgress.ProcessName.Equals(processName))
                {
                    closeProgress.Kill();
                    closeProgress.WaitForExit();
                    break;
                }
            }
        }
        public static bool writeToExcel(MyDel Log, string name, DataTable dt)
        {
            try
            {

                HSSFWorkbook hssfworkbook = new HSSFWorkbook();
                ISheet sheet = hssfworkbook.CreateSheet(name);

                int rowH = 0; //表头
                IRow dataRowHead = sheet.CreateRow(rowH);
                for (int col = 0; col < dt.Columns.Count; col++)
                {
                    ICell cell = dataRowHead.CreateCell(col);
                    cell.SetCellValue(dt.Columns[col].ColumnName);
                }

                int jump = 1; //跳过表头
                for (int row = 0; row < dt.Rows.Count; row++)
                {
                    IRow dataRow = sheet.CreateRow(row+ jump);
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        ICell cell = dataRow.CreateCell(col);
                        cell.SetCellValue(dt.Rows[row][col].ToString());
                    }
                }

                using (FileStream fs = File.OpenWrite(name))
                {
                    hssfworkbook.Write(fs);//向打开的这个xls文件中写入数据                     
                }
                hssfworkbook.Close();
                return true;
            }
            catch (Exception e)
            {
                Log("Error:" + e.ToString());
            }
            return false;
        }//end
        public static bool writeToExcel(MyDel Log, string name, string contents)
        {
            try
            {

                HSSFWorkbook hssfworkbook = new HSSFWorkbook();           
                ISheet sheet = hssfworkbook.CreateSheet(name);
                string[] line = contents.Replace("\r", "").Split('\n');
                for (int i = 0; i < line.Length; ++i)
                {
                    IRow dataRow = sheet.CreateRow(i);
                    string[] field = line[i].Split('\t');
                    for (int j = 0; j < field.Length; j++)
                    {
                        ICell cell = dataRow.CreateCell(j);
                        cell.SetCellValue(field[j]);
                    }
                }
                using (FileStream fs = File.OpenWrite(name))
                {
                    hssfworkbook.Write(fs);//向打开的这个xls文件中写入数据                     
                }
                hssfworkbook.Close();
                return true;
            }
            catch (Exception e)
            {
                Log("Error:" + e.ToString());
            }
            return false;
        }//end
        /// 
        /// 将datatable写入到excel(xls)
        /// 
        /// datatable
        /// 写入的文件路径
        /// 
        public static bool DataTableToExcel(DataTable dt, string filepath)
        {
            bool result = false;
            IWorkbook workbook = null;
            FileStream fs = null;
            IRow row = null;
            ISheet sheet = null;
            ICell cell = null;
            try
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    workbook = new HSSFWorkbook();
                    sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表  
                    int rowCount = dt.Rows.Count;//行数  
                    int columnCount = dt.Columns.Count;//列数  
                    int cellnum;
                    //设置列头  
                    row = sheet.CreateRow(0);//excel第一行设为列头  
                    for (int c = 0; c < columnCount; c++)
                    {
                        cell = row.CreateCell(c);
                        cell.SetCellValue(dt.Columns[c].ColumnName);
                    }

                    //设置每行每列的单元格,  
                    for (int i = 0; i < rowCount; i++)
                    {
                        row = sheet.CreateRow(i + 1);
                        for (int j = 0; j < columnCount; j++)
                        {
                            cell = row.CreateCell(j);//excel第二行开始写入数据
                            //cell.SetCellValue(dt.Rows[i][j].ToString());

                            //保存单元格格式为数字
                            if (j < 2)
                            {
                                cell.SetCellValue(dt.Rows[i][j].ToString());
                            }
                            else
                            {
                                //cell.SetCellValue(int.Parse(dt.Rows[i][j].ToString()));
                                if (dt.Rows[i][j] is DBNull)
                                {
                                    cell.SetCellValue(dt.Rows[i][j].ToString());
                                }
                                else
                                {
                                    cellnum = Convert.ToInt32(dt.Rows[i][j].ToString());
                                    cell.SetCellValue(cellnum);
                                }
                            }
                        }
                    }
                    if (System.IO.File.Exists(filepath))
                    {
                        if (MessageBox.Show("该文件已存在!确定覆盖吗?", "WARNING", MessageBoxButtons.OKCancel) == DialogResult.OK)
                        {
                            File.Delete(filepath);
                        }
                        else
                        {
                            return false;
                        }

                    }
                    using (fs = File.OpenWrite(filepath))
                    {
                        workbook.Write(fs);//向打开的这个xls文件中写入数据
                        result = true;
                    }
                }
                return result;
            }          
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                if (fs != null)
                {
                    fs.Close();
                }
                return false;
            }
        }
    }   
}
   private void printerComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (printerComboBox.SelectedItem != null) //判断是否有选中值
            {
                if (Externs.SetDefaultPrinter(printerComboBox.SelectedItem.ToString())) //设置默认打印机
                {
                    //Log(printerComboBox.SelectedItem.ToString() + "设置为默认打印机成功:"+ printerComboBox.SelectedItem.ToString());
                }
                else
                {
                    Log(printerComboBox.SelectedItem.ToString() + "设置为默认打印机失败!");
                }
            }
        }
               List list = LocalPrinter.GetLocalPrinters(); //获得系统中的打印机列表
                foreach (String s in list)
                {
                    printerComboBox.Items.Add(s); //将打印机名称添加到下拉框中
                }
                printerComboBox.Text = LocalPrinter.DefaultPrinter();

你可能感兴趣的:(日志,C#,c#,开发语言)