Go Premium for a chance to win a PS4. Enter to Win


Barcode Font Replace Space with a UnderScore in VB.NET

Posted on 2008-06-11
Medium Priority
Last Modified: 2013-11-27
Hello all i have been working on this project and i have almost finshed thanks to E.E. I have one last question that should finish up my project i just need to figure out when my users use the space bar it replaces it with a underscore ( _ ) i have all my code correct. Just need this last part figured out.

Thanks i am useing VB.NET Express not sure if this any help but i have been killing my self ont this simple loop issue any help would be greatly appreciated i have listed my code.


Public Class scsdahill
    Private WithEvents mPrintDoc As New System.Drawing.Printing.PrintDocument()
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'UsersDataSet.Users' table. You can move, or remove it, as needed.
        'ComboBox Drop down items listed here
        ComboBox2.Items.Add("San Antonio")
        ComboBox2.Items.Add("Corpus Christi")
        ComboBox2.Items.Add("El Paso")
    End Sub
    Private Sub mPrintDoc_PrintPage(ByVal sender As Object, _
     ByVal e As System.Drawing.Printing.PrintPageEventArgs) _
     Handles mPrintDoc.PrintPage
        Dim timesRomanFont As New Font("TimesRoman", 25)
        Dim barcodeFont As New Font("Code39", 35)
        Dim X, Y As Int32
        X = 25        'Position of first character in line (Column)
        Y = 25        'Position of line (Row) 
        e.Graphics.DrawString("Scan Cover Sheet ", _
            timesRomanFont, Brushes.Black, X, Y, New StringFormat())
        Dim sText As String = "*a" & Me.ComboBox1.Text & "*" & vbCrLf & vbCrLf & _
        "*b" & Me.ComboBox2.Text & "*" & vbCrLf & vbCrLf & _
        "*c" & Me.TextBox1.Text & "*" & vbCrLf & vbCrLf & _
        "*d" & Me.TextBox2.Text & "*" & vbCrLf & vbCrLf & _
        "*e" & Me.TextBox3.Text & "*" & vbCrLf
        Y = 100 'Set new position of new row
        'Print using BarCode font
        e.Graphics.DrawString(sText, barcodeFont, Brushes.Black, X, Y, New StringFormat())
        sText = "User Name:" & Me.ComboBox1.Text & vbCrLf & _
        "Customer Name:" & Me.TextBox2.Text
        Y = 450 'Set new position of new row
        e.Graphics.DrawString(sText, _
            timesRomanFont, Brushes.Black, X, Y, New StringFormat())
    End Sub
    Private Sub btPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btPrint.Click
        mPrintDoc.DefaultPageSettings.Landscape = True
    End Sub
End Class

Open in new window

Question by:vonsean
  • 4
  • 2
  • 2
LVL 11

Expert Comment

ID: 21768115
Your question: "i just need to figure out when my users use the space "

On form load type
MyBase.KeyPreview = True

    Private Sub Form_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If e.KeyCode = Keys.Space Then
            '//Space was pressed
        End If
    End Sub

Author Comment

ID: 21768921
Hmm I input the code but i didnt see it make the changes i dont get a syntax error.
LVL 11

Expert Comment

ID: 21775535
You have to write your code here
  '//Space was pressed
to replace space with _

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

LVL 27

Accepted Solution

planocz earned 2000 total points
ID: 21779194
The code I have does not print the space
Attached FORM 1 and CLASS file
Try it out.
Imports System.Drawing.Printing
Public Class Form1
    Inherits System.Windows.Forms.Form
    Private WithEvents BarcodeDoc As BarcodingParts.TextPrint
#Region " Windows Form Designer generated code "
    Public Sub New()
        'This call is required by the Windows Form Designer.
        'Add any initialization after the InitializeComponent() call
    End Sub
    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
            End If
        End If
    End Sub
    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer
    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents PrintDocument1 As System.Drawing.Printing.PrintDocument
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents PrintPreviewDialog1 As System.Windows.Forms.PrintPreviewDialog
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Form1))
        Me.PrintDocument1 = New System.Drawing.Printing.PrintDocument
        Me.Button1 = New System.Windows.Forms.Button
        Me.PrintPreviewDialog1 = New System.Windows.Forms.PrintPreviewDialog
        Me.Button1.Location = New System.Drawing.Point(196, 224)
        Me.Button1.Name = "Button1"
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Button1"
        Me.PrintPreviewDialog1.AutoScrollMargin = New System.Drawing.Size(0, 0)
        Me.PrintPreviewDialog1.AutoScrollMinSize = New System.Drawing.Size(0, 0)
        Me.PrintPreviewDialog1.ClientSize = New System.Drawing.Size(400, 300)
        Me.PrintPreviewDialog1.Enabled = True
        Me.PrintPreviewDialog1.Icon = CType(resources.GetObject("PrintPreviewDialog1.Icon"), System.Drawing.Icon)
        Me.PrintPreviewDialog1.Location = New System.Drawing.Point(132, 132)
        Me.PrintPreviewDialog1.MinimumSize = New System.Drawing.Size(375, 250)
        Me.PrintPreviewDialog1.Name = "PrintPreviewDialog1"
        Me.PrintPreviewDialog1.TransparencyKey = System.Drawing.Color.Empty
        Me.PrintPreviewDialog1.Visible = False
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 266)
        Me.Name = "Form1"
        Me.Text = "Form1"
    End Sub
#End Region
    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' BarcodeDoc = New BarcodingParts.TextPrint("*00417955*", "Here is Second line from Extended Barcode")
        ' BarcodeDoc.Font = New Font("FREE 3 OF 9 Extended", 30) '<---- Free Font on the internet or add your own
        ' OR USE THIS
        BarcodeDoc = New BarcodingParts.TextPrint("*00417 955*", "Here is Second line from Regular Barcode")
        BarcodeDoc.Font = New Font("FREE 3 OF 9", 30) '<---- Free Font on the internet or add your own
        'For Pre-veiw Printing
        PrintPreviewDialog1.Document = BarcodeDoc
        'For Direct Printing
        Dim PrintDialog1 As New PrintDialog
        'PrintDialog1.Document = BarcodeDoc
    End Sub
    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        BarcodeDoc.PrinterSettings.PrinterName = InitializeDefaultPrinter() '"Zebra"
        BarcodeDoc.DefaultPageSettings.Margins.Left = 10
        BarcodeDoc.DefaultPageSettings.Margins.Right = 10
        BarcodeDoc.DefaultPageSettings.Margins.Top = 40
    End Sub
#Region " Initialize Default Printer "
    Public Function InitializeDefaultPrinter()
        ' Set the specified printer to the default printer for this program. Return
        ' true if the printer was found.
        Dim objprinter As PageSettings = New PageSettings
        Dim strname = objprinter.PrinterSettings.PrinterName
        InitializeDefaultPrinter = strname
    End Function
#End Region
End Class
Imports System.Drawing.Graphics
Public Class TextPrint
    ' Inherits all the functionality of a PrintDocument
    Inherits Printing.PrintDocument
    ' Private variables to hold default font and text
    Private fntPrintFont As Font
    Private strText As String
    Private strText2 As String
    Private PrintBarCodeText As String
    Public Sub New(ByVal Text As String, ByVal Text2 As String)
        ' Sets the file stream
        strText = Text
        strText2 = Text2
    End Sub
    Public Property Text() As String
            Return strText
        End Get
        Set(ByVal Value As String)
            strText = Value
        End Set
    End Property
    Public Property Text2() As String
            Return Trim(strText2)
        End Get
        Set(ByVal Value As String)
            strText2 = Trim(Value)
        End Set
    End Property
    Public Property CodeText() As String
            PrintBarCodeText = Trim(Replace(strText, "*", " "))
            Return PrintBarCodeText
        End Get
        Set(ByVal Value As String)
            If PrintBarCodeText = "" Then
                PrintBarCodeText = Trim(Replace(Value, "*", " "))
            End If
            PrintBarCodeText = Value
        End Set
    End Property
    Protected Overrides Sub OnBeginPrint(ByVal ev As Printing.PrintEventArgs)
        ' Run base code
        ' Sets the default font
        If fntPrintFont Is Nothing Then
            fntPrintFont = New Font("Times New Roman", 12)
        End If
    End Sub
    Public Property Font() As Font
        ' Allows the user to override the default font
            Return fntPrintFont
        End Get
        Set(ByVal Value As Font)
            fntPrintFont = Value
        End Set
    End Property
    Protected Overrides Sub OnPrintPage(ByVal ev As Printing.PrintPageEventArgs)
        ' Provides the print logic for our document
        ' Run base code
        ' Variables
        Static intCurrentChar As Integer
        Dim intPrintAreaHeight, intPrintAreaWidth, intMarginLeft, intMarginTop As Integer
        ' Set printing area boundaries and margin coordinates
        With MyBase.DefaultPageSettings
            intPrintAreaHeight = .PaperSize.Height - .Margins.Top - .Margins.Bottom
            intPrintAreaWidth = .PaperSize.Width - .Margins.Left - .Margins.Right
            intMarginLeft = .Margins.Left 'X
            intMarginTop = .Margins.Top   'Y
        End With
        ' If Landscape set, swap printing height/width
        If MyBase.DefaultPageSettings.Landscape Then
            Dim intTemp As Integer
            intTemp = intPrintAreaHeight
            intPrintAreaHeight = intPrintAreaWidth
            intPrintAreaWidth = intTemp
        End If
        ' Calculate total number of lines
        Dim intLineCount As Int32 = CInt(intPrintAreaHeight / Font.Height)
        ' Initialise rectangle printing area
        Dim rectPrintingArea As New RectangleF(intMarginLeft, intMarginTop, intPrintAreaWidth, intPrintAreaHeight)
        ' Initialise StringFormat class, for text layout
        Dim objSF As New StringFormat(StringFormatFlags.LineLimit)
        ' Figure out how many lines will fit into rectangle
        Dim intLinesFilled, intCharsFitted As Int32
        Dim stringSize As New SizeF
        stringSize = ev.Graphics.MeasureString(Mid(strText, _
                    UpgradeZeros(intCurrentChar)), Font, New SizeF(intPrintAreaWidth, _
                    intPrintAreaHeight), objSF, intCharsFitted, intLinesFilled)
        ' Print the text to the page
        ev.Graphics.DrawString(Mid(strText, _
            UpgradeZeros(intCurrentChar)), Font, Brushes.Black, rectPrintingArea, objSF)
        ' Initialise rectangle printing area for the Barcode Text
        Dim stringFont As New Font("Arial", 12, FontStyle.Bold)
        Dim size As SizeF = ev.Graphics.MeasureString(CodeText, stringFont)
        Dim size2 As SizeF = ev.Graphics.MeasureString(strText2, stringFont)
        Dim BCPrintingArea As New RectangleF(stringSize.Width - size.Width / 2, intMarginTop + stringSize.Height, intPrintAreaWidth, intPrintAreaHeight)
        'Move Second line to center
        Dim moveStr As Integer
        moveStr = stringSize.Width - size2.Width / 2
        moveStr = intMarginLeft + (moveStr / intMarginLeft)
        Dim BCPrintingArea2 As New RectangleF(moveStr, intMarginTop + stringSize.Height + size2.Height, intPrintAreaWidth, intPrintAreaHeight)
        'ADD text Bottom of Barcode
        ev.Graphics.DrawString(CodeText, stringFont, Brushes.Black, BCPrintingArea)
        ev.Graphics.DrawString(strText2, stringFont, Brushes.Black, BCPrintingArea2)
        ' Increase current char count
        intCurrentChar += intCharsFitted
        ' Check whether we need to print more
        If intCurrentChar < strText.Length Then
            ev.HasMorePages = True
            ev.HasMorePages = False
            intCurrentChar = 0
        End If
    End Sub
    Public Function UpgradeZeros(ByVal Input As Integer) As Integer
        ' Upgrades all zeros to ones
        ' - used as opposed to defunct IIF or messy If statements
        If Input = 0 Then
            Return 1
            Return Input
        End If
    End Function
End Class

Open in new window


Author Comment

ID: 21805767
Cool I will try it today, I have been out of town for the week. I will try it today I really appreceate all of the help from everyone.
I will try it tonight thanks again!!


Author Comment

ID: 21875061
Sorry i didnt get it to work i get an error that i dont understand, maybe i did something wrong i copied the code to a blank form and i add my text boxs and so on then it removes them. Im not sure what i am doing wrong.
LVL 27

Expert Comment

ID: 21875615
for this example you should not need any other code added to it.
Once you see how it runs you then can break up the parts and create your own form project.

Author Closing Comment

ID: 31466381
Thanks It worked i had to do some changes but i was able to figure out how to implement it in to my code.


Featured Post

Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Loops Section Overview

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question