1、控件下载。

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

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

2、控件的注册。

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

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

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

  HKEY_CLASSES_ROOT\TypeLib\{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:\windows\barcodex.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控件预览和打印一维码的更多相关文章

  1. FileUpload控件预览图片

    HTML代码: <tr> <td class="auto-style1">上传图片:</td> <td> <asp:FileU ...

  2. DevExpress winform XtraEditor常用控件

    最近在公司里面开始使用DevExpress winform的第三方控件进行开发和维护,这里整理一些常用控件的资料以便于后续查看 ComboBoxEdit 这个控件和winform自带的控件差不多,使用 ...

  3. WinForm容器内控件批量效验是否允许为空?设置是否只读?设置是否可用等方法分享

    WinForm容器内控件批量效验是否允许为空?设置是否只读?设置是否可用等方法分享 在WinForm程序中,我们有时需要对某容器内的所有控件做批量操作.如批量判断是否允许为空?批量设置为只读.批量设置 ...

  4. Winform中checklistbox控件的常用方法

    Winform中checklistbox控件的常用方法最近用到checklistbox控件,在使用其过程中,收集了其相关的代码段1.添加项checkedListBox1.Items.Add(" ...

  5. {VS2010C#}{WinForm}{ActiveX}VS2010C#开发基于WinForm的ActiveX控件

    在VS2010中使用C#开发基于WinForm的ActiveX控件 常见的一些ActiveX大部分是使用VB.Delphi.C++开发,使用C#开发ActiveX要解决下面三个问题: 使.NET组件可 ...

  6. Atitit. .net c# web 跟客户端winform 的ui控件结构比较

    Atitit. .net c# web 跟客户端winform 的ui控件结构比较 .net   4.5 webform Winform 命名空间 System.Web.UI.WebControls ...

  7. WinForm窗体及其控件的自适应

    3步骤: 1.在需要自适应的Form中实例化全局变量   AutoSizeFormClass.cs源码在下方 AutoSizeFormClass asc = new AutoSizeFormClass ...

  8. WinForm界面布局控件WeifenLuo.WinFormsUI.Docking"的使用 (二)

    WinForm界面布局控件WeifenLuo.WinFormsUI.Docking"的使用 (二) 编写人:CC阿爸 2015-1-29 今天我想与大家继续一起分享这一伟大的控件.有兴趣的同 ...

  9. .Net2.0 --Winform结合WebBrowser控件和Socket老技术来实现另类Push~

    原文:.Net2.0 --Winform结合WebBrowser控件和Socket老技术来实现另类Push~ 目前的企业级开发比较流行的是Web2.0技术,但是由于Web技术基于请求--响应的交互模式 ...

随机推荐

  1. nmap安装和使用

    nmap安装和使用 安装 官网地址 https://nmap.org/download.html 许多流行的Linux发行版(Redhat.Mandrake.Suse等)都使用RPM软件包管理系统,方 ...

  2. kafka producer 概要(看源码前,最好能掌握)

        kafakproducer概要(看源码前,最好能理解) 摘要 kafak 被设计用来作为一个统一的平台来处理庞大的数据的实时工具,在设计上有诸多变态的要求 它必须具有高吞吐量才能支持大量事件流 ...

  3. 10万级etl批量作业自动化调度工具Taskctl之轻量级Web应用版

    什么是批量作业: 批量处理是银行业整个信息后台最为重要的技术形态,也是银行核心信息资产数据的分享.传输.演化的重要技术手段.有调查指出,全球70%的数据是经过批量处理得以再次使用,可见批量处理在整个信 ...

  4. 定时器:Django-crontab

    定时器是平时编程中比较常用的,今天分享一个Django里非常好用又简单的定时亲:Django-crontab.这个真的是非常的简单好用,比celery+Django执行周期任务简单的多 首先下载dja ...

  5. 第7.22节 Python中使用super调用父类的方法

    第7.22节 Python中使用super调用父类的方法 前面章节很多地方都引入了super方法,这个方法就是访问超类这个类对象的.由于super方法的特殊性,本节单独谈一谈super方法. 一.su ...

  6. PyQt(Python+Qt)学习随笔:QScrollArea的widgetResizable属性

    老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 滚动区域的widgetResizable属性用于控制滚动区域的内容部署层是否应跟随滚动区域的大小变化 ...

  7. PyQt(Python+Qt)学习随笔:QAbstractItemView的alternatingRowColors属性

    老猿Python博文目录 老猿Python博客地址 alternatingRowColors属性用于控制视图中不同行记录背景色是否使用交替不同的颜色. 如果此属性为True,则将使用QPalette. ...

  8. 网鼎杯 fakebook

    这道题目登录之后我们可以看到有join和login login即登录,join即注册 我们通过查看robots.txt可以知道 有源代码泄露. 先将泄露的源码下载下来审计一波 <?php cla ...

  9. tesseract-ocr 图片文字识别

    本篇记录下python识别图片中的文字 所需的安装配置:  安装库: pip install pytesseract pip install PILLOW   安装 Tesseract-OCR软件: ...

  10. 使用k8s部署springboot+redis简单应用

    准备 本文将使用k8s部署一个springboot+redis应用,由于是示例,所以功能比较简单,只有设置值和获取值两个api. (1)设置值 (2)获取值 构建Web应用 (1)创建一个spring ...