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