2011年2月26日 星期六

產生條碼

感謝 Brad Barnhill 及他post的文章 (Thanks to Barnhill, Brad)

Barnhill 撰寫了產生條碼的DLL函式庫,讓我們可以快速地產生需要的條碼,這個已經困擾我十幾年的需求。

以下產生預設是128碼,可同時包含英文與數字,但為了簡化程式,只能輸入最多24個英文字或46個數字。

 

1. 首先加入參考 BarcodeLib.dll ,如下圖

 


 

2. 照例布置所需要的物件如下圖


最下方是一個picturebox1

 

3. 程式如下

一開始先imports函示庫

 

Imports BarcodeLib

 

 

  Dim b As BarcodeLib.Barcode = New BarcodeLib.Barcode()

//以下這幾行程式便可產生條碼圖形

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim type As BarcodeLib.TYPE = BarcodeLib.TYPE.CODE128
        b.IncludeLabel = True
        Try
            PictureBox1.Image = b.Encode(type, TextBox1.Text.Trim)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try


    End Sub

 

 //條碼存檔

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim sfd As New SaveFileDialog
        sfd.Filter = "BMP (*.bmp)|*.bmp|GIF (*.gif)|*.gif|JPG (*.jpg)|*.jpg|PNG (*.png)|*.png|TIFF (*.tif)|*.tif"
        sfd.FilterIndex = 2
        sfd.AddExtension = True
        If (sfd.ShowDialog = DialogResult.OK) Then
            Dim savetype As BarcodeLib.SaveTypes = SaveTypes.UNSPECIFIED
            Select Case (sfd.FilterIndex)
                Case 1
                    savetype = BarcodeLib.SaveTypes.BMP

                Case 2
                    savetype = BarcodeLib.SaveTypes.GIF
                Case 3
                    savetype = BarcodeLib.SaveTypes.JPG
                Case 4
                    savetype = BarcodeLib.SaveTypes.PNG
                Case 5
                    savetype = BarcodeLib.SaveTypes.TIFF
            End Select
            b.SaveImage(sfd.FileName, savetype)
        End If

 

    End Sub

 

 

通常產生的條碼會需要列印出來,此時加入PrintDocument及PrintPreviewDialog控制項,windows form加入一個預覽列印的按鈕Button3,接著再加入以下程式碼

 

  'printdocument包含所有列印所需要的資訊,
    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        e.Graphics.DrawImage(Me.PictureBox1.Image, 0, 0)
        e.Graphics.PageUnit = GraphicsUnit.Inch

    End Sub


    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        PrintPreviewDialog1.Document = PrintDocument1 'PrintPreviewDialog associate with PrintDocument.
        PrintPreviewDialog1.ShowDialog() 'open the print preview

    End Sub

完成後執行預覽列印的畫面如下:

 


沒有留言:

張貼留言