winform使用Barcodex控件预览和打印一维码

摘要:
包含条形码的dll文件。ocx控件、条形码帮助文档和两个winform控件。此示例用于确定注册表_ CLASSES_ ROOTTypeLib中的HKEY是否包含条形码.ocx项。如果条形码。ocx控件已注册,将生成相应的项。注意:此项的最后一个{8E515444-86DF-11D3-A630-44453540001}是条形码的唯一GUID值。ocx控制。System.Diagnostics.Process。开始登记它名为“install.bat”,内容为“regsvr32.execarcodex.ocx”。查找名为BarcodeXbyFathSoftware、路径为c:windowsarcdex的项目。ocx,选择它并添加它。24 PrintDocumentpd=空;//打印对象声明,然后在循环中实例化对象。

1、控件下载。

  http://files.cnblogs.com/files/masonblog/barcodex.zip 。

  包含barcodex.ocx控件、barcodex帮助文档、两个winform控件的dll文件。

2、控件的注册。

(1)检测控件是否注册(方法不唯一)。

  本例使用的是判断注册表中 HKEY_CLASSES_ROOTTypeLib 是否包含barcodex.ocx的项。

  如果注册了barcodex.ocx控件,则会生成对应的项。

  HKEY_CLASSES_ROOTTypeLib{8E515444-86DF-11D3-A630-444553540001} 。

  注:该项最后的 {8E515444-86DF-11D3-A630-444553540001} 为barcodex.ocx控件唯一GUID值。

(2)注册ocx控件(提供三种方法)

  ①调用命令提示符。(barcodex.ocx必须在应用程序的根目录)

    System.Diagnostics.Process.Start("regsvr32", "barcodex.ocx /s");进行注册。

  ②调用bat。(与①类似,未使用过)

    在应用程序的根目录编辑好一个bat。命名为" install.bat ",内容为“ regsvr32.exe barcodex.ocx ”。barcodex.ocx必须在应用程序的根目录。

    再调用System.Diagnostics.Process.Start("regsvr32", "install.bat ");进行注册。

  ③调用ocx的注册入口函数。(本例使用)

    Ⅰ、将文件复制到" C:\windows "目录下(文件目录是次要,笔者是考虑误删,才选择此目录。)

    Ⅱ、声明调用的函数(需要引用 using System.Runtime.InteropServices; )

       [DllImport("C:\Windows\barcodex.ocx")]
            public static extern int DllRegisterServer();//注册时用
            [DllImport("C:\Windows\barcodex.ocx")]
            public static extern int DllUnregisterServer();//取消注册时用

    Ⅲ、自定义的注册方法。      

      public static bool DLLRegister()

      {

        int i = DllRegisterServer();
        if (i >= 0)
         {
          return true;
        }
        else
        {
          return false;
        }

      }

3、控件的引用。

(1)引用AxInterop.BARCODEXLib.dll和Interop.BARCODEXLib.dll文件。

(2)工具箱->所有windows窗体->右键 选择项->选择com组件 。

  找到名称为BarcodeX by Fath Software,路径为c:windowsarcodex.ocx 的项,选中,添加。即可完成添加。

4、拖入条形码控件到winform窗体中,设置Name为axBCX。

5、预览一维码。

(1)axBCX.BarcodeType=BARCODEXLib.bcxTypeEnum.bcxCode128;//设置条形码类型,

(2)axBCX.Caption = "123456789";//要显示的条形码

(3)axBCX.Height=150;//条形码的高度

(4)axBCX.Width=80;//条形码的宽度

(5)axBCX.Title="条形码的预览";//条形码的标题

至此,即可完成Barcodex条形码的预览功能。

6、打印条形码。

(1)原理:将条形码区域截取为image进行打印(两种方法)。

  ①使用axBCX.Picture 属性,即可获取其对应的image对象,但是此属性需要[ComAliasName("stdole.IPictureDisp")](stdole)的支持,此为office扩展,客户机器不一定安装,所以不建议使用。

  ②使用axBCX.CreateBMP();方法,将条形码截取为bmp图片,再进行打印。

(2)打印实现。

  ①基本流程

  

  1         /// <summary>
  2         /// 打印按钮
  3         /// </summary>
  4         /// <param name="sender"></param>
  5         /// <param name="e"></param>
  6         private void btnPrint_Click(object sender, EventArgs e)
  7         {
  8             /*获取值*/
  9             string sSchoolName = txtSchoolName.Text.Trim();//学校名称
 10             //开始截至次数
 11             string sBeginBarcode = txtBeginBarcode.Text.Trim();//(000001)
 12             string sEndBarcode = txtEndBarcode.Text.Trim();//(000009)
 13             string sRepeatCount = txtRepeatCount.Text.Trim();//3,代表每个条形码打印的次数
 14             //标签高宽
 15             decimal dLabelHeight = nudLabelHeight.Value;
 16             decimal dLabelWidth = nudLabelWidth.Value;
 17             //边距
 18             decimal dTopMargin = nudTopMargin.Value;//条形码在整个标签的上边距
 19             decimal dLeftMargin = nudLeftMargin.Value;//条形码在整个标签的左边距 
 20             //显示内容
 21             bool bIsShowSchoolName = chkShowSchoolName.Checked;//是否显示标题
 22             //条形码的码制
 23             string sBarcode = cmbBarcode.SelectedItem.ToString();//选择的条形码的码制。可以写死,可以使用下拉框供选择。
 24        PrintDocument pd=null; //打印对象的声明,之后在循环再进行对象的实例化。
 25             try
 26             {
 27                 /*转换*/
 28                 //开始截至次数
 29                 //判断条形码中是否含有字母
 30                 bool bIsHaveLetter = false;
 31                 string sLetterBeginBarcode = string.Empty;//开始条形码字母部分
 32                 string sNumberBeginBarcode = string.Empty;//开始条形码数字部分
 33                 string sLetterEndBarcode = string.Empty;//截止条形码字母部分
 34                 string sNumberEndBarcode = string.Empty;//截止条形码数字部分
 35                 if (char.IsLetter(sBeginBarcode[0]))
 36                 {
 37                     bIsHaveLetter = true;
 38                     sLetterBeginBarcode = sBeginBarcode.Substring(0, 1);
 39                     sNumberBeginBarcode = sBeginBarcode.Substring(1, sBeginBarcode.Length - 1);
 40                 }
 41 
 42                 if (char.IsLetter(sEndBarcode[0]))
 43                 {
 44                     bIsHaveLetter = true;
 45                     sLetterEndBarcode = sEndBarcode.Substring(0, 1);
 46                     sNumberEndBarcode = sEndBarcode.Substring(1, sEndBarcode.Length - 1);
 47                 }
 48                 long lBeginBarcode = bIsHaveLetter ? long.Parse(sNumberBeginBarcode) : long.Parse(sBeginBarcode);
 49                 long lEndBaecode = bIsHaveLetter ? long.Parse(sNumberEndBarcode) : long.Parse(sEndBarcode);
 50                 int iRepeatCount = int.Parse(sRepeatCount);
 51 
 52                 //删除之前生成的图片
 53                 Utility.DeletePreviewBarcode();
 54                 //预览图片的地址
 55                 string sPreviewPath = Utility.ConfigGetItem("PreviewPath"); //<add key="PreviewPath" value="C:\BarcodePreview"/> 生成的bmp文件保存的路径。
 56                 //设置边距
 57                 Margins margin = new Margins(Utility.GetPixelByWidth(dLeftMargin), 0, Utility.GetPixelByHeight(dTopMargin), 0);
 58                 59                 //控件设置
 60                 axBCX.BarcodeType = Utility.GetbcxTypeByBarcode(sBarcode);
 61                 axBCX.Height = Utility.GetPixelByWidth(dLabelHeight - dTopMargin);
 62                 axBCX.Width = Utility.GetPixelByHeight(dLabelWidth - dLeftMargin);
 63 
 64                 for (long i = lBeginBarcode; i <= lEndBaecode; i++)
 65                 {
 66                     for (int j = 0; j < iRepeatCount; j++)
 67                     {
 68                         pd=new PrintDocument();//重新示例化打印对象,防止pd_PrintPage()方法附加多次导致堆积。 69                         pd.DefaultPageSettings.Margins = margin; 
 70                         axBCX.Title = "";
 71                         //条形码控件重新赋值(打印时获取image)
 72                         if (bIsHaveLetter)
 73                         {
 74                             axBCX.Caption = sLetterBeginBarcode + i.ToString().PadLeft(sBeginBarcode.Length - 1, '0');
 75                         }
 76                         else
 77                         {
 78                             axBCX.Caption = i.ToString().PadLeft(sBeginBarcode.Length, '0');
 79                         }
 80                         //创建对应的条形码图片
 81                         string sFileName = sPreviewPath + "\" + axBCX.Caption + ".bmp";
 82                         axBCX.CreateBMP(sFileName, axBCX.Width, axBCX.Height);
 83                         //横向打印
 84                         pd.DefaultPageSettings.Landscape = true;
 85                         //页面尺寸
 86                         pd.DefaultPageSettings.PaperSize = new PaperSize("Custom", Utility.GetPixelByWidth(dLabelWidth), Utility.GetPixelByWidth(dLabelHeight));
 87                         pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
 88                         pd.Print();
 89                     }
 90                 }
 91                 //删除之前生成的图片
 92                 Utility.DeletePreviewBarcode();
 93             }
 94             catch (Exception ex)
 95             {
 96                 string str = Utility.GetExceptionMsg(ex, ex.ToString());
 97                 Utility.WriteLog(str);
 98                 //获取程序执行异常的提示信息
 99                 MessageBox.Show("打印失败!");
100             }
101         }
102 
103         //打印事件处理
104         private void pd_PrintPage(object sender, PrintPageEventArgs e)
105         {
106             //显示内容
107             bool bIsShowSchoolName = chkShowSchoolName.Checked;
108             //左边距
109             float fLeftMargin = float.Parse(nudLeftMargin.Value.ToString());
110             //1、获取对应的条形码图片
111             string sPreviewPath = Utility.ConfigGetItem("PreviewPath");
112             string sFileName = sPreviewPath + "\" + axBCX.Caption + ".bmp";
113             Image imgBarcode = Image.FromFile(sFileName);
114             Image imgAll;
115             //2.1、显示学校名称
116             if (bIsShowSchoolName)
117             {
118                 //2.1.1、Title的图片
119                 Image imgTitle = Utility.CreateImage(txtSchoolName.Text, false, 8, imgBarcode.Width, imgBarcode.Height, Utility.MarginLeftByBarcodeLength(axBCX.Caption, fLeftMargin));
120                 //2.1.2、合并图片
121                 imgAll = Utility.MergeImage(imgBarcode, imgTitle);
122                 imgTitle.Dispose();
123             }
124             //2.2、不显示学校名称
125             else
126             {
127                 imgAll = imgBarcode;
128             }
129             //Image image = axBCX.Picture;
130             int x = e.MarginBounds.X;
131             int y = e.MarginBounds.Y;
132             int width = imgAll.Width;
133             int height = imgAll.Height;
134             //打印区域的大小,是Rectangle结构,元素包括左上角坐标:Left和Top,宽和高.
135             Rectangle destRect = new Rectangle(x, y, width, height);
136             e.Graphics.DrawImage(imgAll, destRect, 0, 0, imgAll.Width, imgAll.Height, System.Drawing.GraphicsUnit.Pixel);
137             //释放资源(否则删除操作无法完成)                        
138             imgBarcode.Dispose();
139             imgAll.Dispose();
140         }

②Utility类中使用的方法。

  1 public static class Utility
  2 {        
  3         /// <summary>
  4         /// 获取键为keyName的项的值
  5         /// </summary>
  6         /// <param name="keyName"></param>
  7         /// <returns></returns>
  8         public static string ConfigGetItem(string keyName)
  9         {
 10             //返回配置文件中键为keyName的项的值  
 11             return ConfigurationManager.AppSettings[keyName];
 12         }
 13         #region 输入长度(毫米mm)获取匹配分辨率下的像素数
 14         /// <summary> 
 15         /// 根据输入的宽度获取对应的 x 轴的像素
 16         /// </summary>
 17         /// <param name="dWidth"></param>
 18         /// <returns></returns>
 19         public static int GetPixelByWidth(decimal dWidth)
 20         {
 21             //声明变量
 22             int iDpiX = 96;//x轴DPI默认为96
 23             double dPixelX = 0;//讲过计算的像素数
 24             //获取屏幕x轴的DPI
 25             iDpiX = PrimaryScreen.DpiX;
 26             //根据换算关系计算对应的像素数
 27             dPixelX = ((double)dWidth) * iDpiX / 25.4;
 28             //转换为int类型返回
 29             return (int)dPixelX;
 30         }
 31         /// <summary>
 32         /// 根据输入的高度获取对应的 y 轴的像素
 33         /// </summary>
 34         /// <param name="dHeight"></param>
 35         /// <returns></returns>
 36         public static int GetPixelByHeight(decimal dHeight)
 37         {
 38             //声明变量
 39             int iDpiY = 96;//Y轴DPI默认为96
 40             double dPiYelY = 0;//讲过计算的像素数
 41             //获取屏幕Y轴的DPI
 42             iDpiY = PrimaryScreen.DpiY;
 43             //根据换算关系计算对应的像素数
 44             dPiYelY = ((double)dHeight) * iDpiY / 25.4;
 45             //转换为int类型返回
 46             return (int)dPiYelY;
 47         }
 48         #endregion
 49          #region 图片操作方法(生成文字图片、合并图片等)
 50         /// <summary>
 51         /// 生成文字图片
 52         /// </summary>
 53         /// <param name="text"></param>
 54         /// <param name="isBold"></param>
 55         /// <param name="fontSize"></param>
 56         public static Image CreateImage(string text, bool isBold, int fontSize, int wid, int high, float leftMargin)
 57         {
 58             Font font;
 59             if (isBold)
 60             {
 61                 font = new Font("Arial", fontSize, FontStyle.Bold);
 62             }
 63             else
 64             {
 65                 font = new Font("Arial", fontSize, FontStyle.Regular);
 66             }
 67             //绘笔颜色
 68             SolidBrush brush = new SolidBrush(Color.Black);
 69             StringFormat format = new StringFormat(StringFormatFlags.NoClip);
 70 
 71             Bitmap image = new Bitmap(wid, high);
 72             Graphics g = Graphics.FromImage(image);
 73 
 74             SizeF sizef = g.MeasureString(text, font, PointF.Empty, format);//得到文本的宽高
 75             int width = (int)(sizef.Width + 1);
 76             int height = (int)(sizef.Height + 2);
 77             image.Dispose();
 78             
 79             image = new Bitmap(wid, height);
 80             g = Graphics.FromImage(image);
 81             g.Clear(Color.White);//透明            
 82             float fLeft = leftMargin; //左边距
 83             RectangleF rect = new RectangleF(fLeft, 0, width, height);
 84             //绘制图片
 85             g.DrawString(text, font, brush, rect);
 86 
 87             //释放对象
 88             g.Dispose();
 89             return image;
 90         }
 91 
 92         /// <summary>
 93         /// 合并图片
 94         /// </summary>
 95         /// <returns></returns>
 96         public static Bitmap MergeImage(Image imgBack, Image img, int xDeviation = 0, int yDeviation = 0)
 97         {
 98             Bitmap bmp = new Bitmap(imgBack.Width, imgBack.Height);
 99             Graphics g = Graphics.FromImage(bmp);
100             g.Clear(Color.White);
101             g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height); //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);     
102             //g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1,1,1);//相片四周刷一层黑色边框    
103             //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);    
104             g.DrawImage(img, 0, 0, img.Width, img.Height);
105             GC.Collect();
106             return bmp;
107         }
108         #endregion
109 }         

③PrimaryScreen类

  1  /// <summary>
  2     /// 获取屏幕分辨率属性
  3     /// </summary>
  4     public class PrimaryScreen
  5     {
  6         #region Win32 API
  7         [DllImport("user32.dll")]
  8         static extern IntPtr GetDC(IntPtr ptr);
  9         [DllImport("gdi32.dll")]
 10         static extern int GetDeviceCaps(
 11        IntPtr hdc, // handle to DC
 12        int nIndex // index of capability
 13        );
 14         [DllImport("user32.dll", EntryPoint = "ReleaseDC")]
 15         static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDc);
 16         #endregion
 17         #region DeviceCaps常量
 18         const int HORZRES = 8;
 19         const int VERTRES = 10;
 20         const int LOGPIXELSX = 88;
 21         const int LOGPIXELSY = 90;
 22         const int DESKTOPVERTRES = 117;
 23         const int DESKTOPHORZRES = 118;
 24         #endregion
 25 
 26         #region 属性
 27         /// <summary>
 28         /// 获取屏幕分辨率当前物理大小
 29         /// </summary>
 30         public static Size WorkingArea
 31         {
 32             get
 33             {
 34                 IntPtr hdc = GetDC(IntPtr.Zero);
 35                 Size size = new Size();
 36                 size.Width = GetDeviceCaps(hdc, HORZRES);
 37                 size.Height = GetDeviceCaps(hdc, VERTRES);
 38                 ReleaseDC(IntPtr.Zero, hdc);
 39                 return size;
 40             }
 41         }
 42         /// <summary>
 43         /// 当前系统DPI_X 大小 一般为96
 44         /// </summary>
 45         public static int DpiX
 46         {
 47             get
 48             {
 49                 IntPtr hdc = GetDC(IntPtr.Zero);
 50                 int DpiX = GetDeviceCaps(hdc, LOGPIXELSX);
 51                 ReleaseDC(IntPtr.Zero, hdc);
 52                 return DpiX;
 53             }
 54         }
 55         /// <summary>
 56         /// 当前系统DPI_Y 大小 一般为96
 57         /// </summary>
 58         public static int DpiY
 59         {
 60             get
 61             {
 62                 IntPtr hdc = GetDC(IntPtr.Zero);
 63                 int DpiX = GetDeviceCaps(hdc, LOGPIXELSY);
 64                 ReleaseDC(IntPtr.Zero, hdc);
 65                 return DpiX;
 66             }
 67         }
 68         /// <summary>
 69         /// 获取真实设置的桌面分辨率大小
 70         /// </summary>
 71         public static Size DESKTOP
 72         {
 73             get
 74             {
 75                 IntPtr hdc = GetDC(IntPtr.Zero);
 76                 Size size = new Size();
 77                 size.Width = GetDeviceCaps(hdc, DESKTOPHORZRES);
 78                 size.Height = GetDeviceCaps(hdc, DESKTOPVERTRES);
 79                 ReleaseDC(IntPtr.Zero, hdc);
 80                 return size;
 81             }
 82         }
 83 
 84         /// <summary>
 85         /// 获取宽度缩放百分比
 86         /// </summary>
 87         public static float ScaleX
 88         {
 89             get
 90             {
 91                 IntPtr hdc = GetDC(IntPtr.Zero);
 92                 int t = GetDeviceCaps(hdc, DESKTOPHORZRES);
 93                 int d = GetDeviceCaps(hdc, HORZRES);
 94                 float ScaleX = (float)GetDeviceCaps(hdc, DESKTOPHORZRES) / (float)GetDeviceCaps(hdc, HORZRES);
 95                 ReleaseDC(IntPtr.Zero, hdc);
 96                 return ScaleX;
 97             }
 98         }
 99         /// <summary>
100         /// 获取高度缩放百分比
101         /// </summary>
102         public static float ScaleY
103         {
104             get
105             {
106                 IntPtr hdc = GetDC(IntPtr.Zero);
107                 float ScaleY = (float)(float)GetDeviceCaps(hdc, DESKTOPVERTRES) / (float)GetDeviceCaps(hdc, VERTRES);
108                 ReleaseDC(IntPtr.Zero, hdc);
109                 return ScaleY;
110             }
111         }
112         #endregion
113     }

 ④注:

Ⅰ、//删除之前生成的图片
        Utility.DeletePreviewBarcode();

        #region 删除条形码预览文件夹下的所有图片
        /// <summary>
        /// 删除预览的条形码图片
        /// </summary>
        public static void DeletePreviewBarcode()
        {
            string sPath = string.IsNullOrEmpty(ConfigGetItem("PreviewPath")) ? "C:\BarcodePreview" : Utility.ConfigGetItem("PreviewPath");
            //如果存在先删除其中的文件
            if (Directory.Exists(sPath))
            {
                Directory.Delete(sPath, true);
            }
            Directory.CreateDirectory(sPath);
        }
        #endregion

免责声明:文章转载自《winform使用Barcodex控件预览和打印一维码》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Linux环境依赖库离线安装网页支付页面代码下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

淘宝网Open API 入门教程

淘宝网Open API 入门教程 淘宝网的Open API开放将近一年了,越来越多的人(包括已工作的和在校的大学生)都在使用淘宝的Open API,有不少ISV应用已上架盈利了。我也使用淘宝的Open Api也大半年了。不过了,由于阿里软件的文档比较的乱,让很多初学者分不清头绪(注:淘宝网的Open API是开放在阿里软件的一个平台上,是什么服务集群平台吧...

WebSocket实时消息推送

最近在项目中,使用到了WebSocket来实时推送服务器的数据到客户端,今天来记录总结一下。 想要使用WebSocket来实时推送数据,首先需要服务器与客户端直接建立连接,也就是握手(HTTP协议) 每5秒钟发生一个心跳@Scheduled(cron = "0/5 * * * * ? ") public void sendHeart() {...

用Javascript进行HTML转义(分享)

  众所周知页面上的字符内容通常都需要进行HTML转义才能正确显示,尤其对于Input,Textarea提交的内容,更是要进行转义以防止javascript注入攻击。   通常的HTML转义主要是针对内容中的"<",">","&",以及空格、单双引号等。但其实还有很多字符也需要进行转义。具体的可以参考这篇文章。   ** 1、HTML转...

C#中ASCII码学习心得

1.利用调用ASCIIEncoding类来实现各种转换。如简单个ACS码和int转换。 ***利用(int)ASCIIEncoding类对象.GetBytes(character)[0]得到整数; public static int Asc(string character){if (character.Length == 1){ System.Text....

C# WinForm窗体界面设置问题

设置方法:  一:Form对象  属性:  设计中的Name:窗体类的类名AcceptButton:窗口的确定按钮CancelButton:窗口按ESC的取消按钮  1.外观  Backcolor:背景颜色Forecolor:字体颜色backgroundImage:背景图片Font:设置字体Formborderstyle:边框样式,常用Fixedsingl...

数据库连接池

连接池本质上是一组java架包,介于java应用程序与JDBC数据库物理链接之间,帮助应用程序管理链接。 通过连接池预先同数据库建立一些连接放在内存中(即连接池中),应用程序需要建立数据库连接时直接到从接池中申请一个连接使用,用完后由连接池回收该连接,从而达到连接复用,减少资源消耗的目的。 DBCP连接池:DBCP(DataBase connection...