Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Getting Printer Port Name

Posted on 2006-07-12
5
Medium Priority
?
1,196 Views
Last Modified: 2007-12-19
I would greatly, greatly appreciate someones help with this.  I have an application I'm working on and I need to be able to get the Printer Port Name of a printer in VB.NET 2005.  I am already able to get the printer name using the statement

System.Drawing.Printing.PrinterSettings.InstalledPrinters.Item(i)

What I would like to do is after getting the printer name, is to retrieve its port name.  Unfortunetly, I have been unable to find any solid information on this.

Thank you for your help!

Nick
0
Comment
Question by:nconfer
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
5 Comments
 
LVL 24

Expert Comment

by:Jeff Certain
ID: 17094714
Doesn't look like the news is good... (from VS2005 help)
In Visual Basic 6.0, the Printers collection is used to return information about available printers on a system. Typically, you iterate through the Printers collection to find a printer with certain attributes and then set that printer to be the default printer for your application. For example, you might choose a laser printer instead of a dot matrix printer.

In Visual Basic 2005, there is no direct equivalent for the Printers collection, and the model has changed: Rather than choosing a printer for your application, you should allow your users to make their own choices.

A PrintDialog component can be used to present a list of available printers to the user. Properties for the printer selected by the user can be retrieved using the PrinterSettings class.

The Printers collection in Visual Basic 6.0 has two properties: Item and Count. The PrintDialog component has no equivalent properties. The PrinterSettings class has an InstalledPrinters collection with Item and Count; however, this is a String collection and cannot be used to query the attributes of a printer.

However, this article might be helpful is finding a work-around
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs05/html/vb05legacyhardware.asp
0
 
LVL 1

Author Comment

by:nconfer
ID: 17096752
Yeah I've seen that page before as well.  However, I when I did a google search to get the printer port name they did mention that there was ways to do it, I have just been unable to figure it out.

To clarify, I need to get the printer port name because I need to delete all printers that have a specific printer port (the printers that were installed previously with this program).  I am unable to simply delete the printers by there name because it is possible the user has named their printer the same thing (and I don't want to delete any printers the user installed on their own).  So it is important I specifically get the printer port name.  

I found a similar question asked at this URL http://www.thescripts.com/forum/thread348050.html to get the printer port name and the response said the following...

You can use the WMI class 'Win32_Printer' and get its port name
('PortName' property). You will find samples for using WMI with VB.NET
on the web.


Unfortunetly, I have been unable to find any solid examples on the web for this.  Hopefully this helps, could anyone assist me in finding a solution.  I would greatly appreciate it.
0
 
LVL 1

Author Comment

by:nconfer
ID: 17104689
I am extremely close to gettng the printer port name.  I have code that I have converted from C# to VB.net.  The problem is I'm only getting the first characted of everything.  So the printer name returns as P and the the port name as C since the port is located in the C:

below is the code.  I just created a new vb.net app and added in a button.  Before I post the full code, this is the exact line I'm having trouble converting, which is very likely why I'm only getting a single character returned for each thing

The line of C# code I'm trying to convert to VB.NET

PRINTER_INFO_2 PrinterInfo = (PRINTER_INFO_2) Marshal.PtrToStructure(pPrinterInfo, typeof(PRINTER_INFO_2));

This is how I converted it.  It is returning the vals including port name, but only the first character

Dim PrinterInfo As PRINTER_INFO_2 = CType(Marshal.PtrToStructure(pPrinterInfo, GetType(PRINTER_INFO_2)), PRINTER_INFO_2)






Finally here is the full code I have.  You can duplicate this easily by opening a new project and butting in a single button.


Option Strict Off
Option Explicit On

Imports System.Runtime.InteropServices

Public Class Form1

    Public Declare Function OpenPrinter Lib "winspool.drv" Alias "OpenPrinterA" (ByVal pPrinterName As String, ByRef hPrinter As Integer, ByRef pDefault As IntPtr) As Integer

    Private Declare Function ClosePrinter Lib "winspool.drv" (ByVal hPrinter As IntPtr) As Integer

    Private Declare Function GetPrinter Lib "winspool.drv" Alias "GetPrinterW" (ByVal hPrinter As IntPtr, ByVal dwLevel As Integer, ByVal pPrinter As IntPtr, ByVal cbBuf As Integer, ByRef pcbNeeded As Integer) As Integer

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi)> Public Structure PRINTER_INFO_2
        Dim pServerName As String
        Dim pPrinterName As String
        Dim pShareName As String
        Dim pPortName As String
        Dim pDriverName As String
        Dim pComment As String
        Dim pLocation As String
        Dim pDevMode As Integer
        Dim pSepFile As String
        Dim pPrintProcessor As String
        Dim pDatatype As String
        Dim pParameters As String
        Dim pSecurityDescriptor As Integer
        Dim Attributes As Integer
        Dim Priority As Integer
        Dim DefaultPriority As Integer
        Dim StartTime As Integer
        Dim UntilTime As Integer
        Dim Status As Integer
        Dim cJobs As Integer
        Dim AveragePPM As Integer
    End Structure

    Private mStatus As UInt32
    Private mJobs As UInt32
    Private mDriver As String
    Private mDevice As String
    Private mPort As String

    Public Function getPrinterInfo(ByVal sName As String) As Boolean
        Try
            Dim hPrinter As IntPtr = IntPtr.Zero
            Dim pPrinterInfo As IntPtr = IntPtr.Zero
            If (OpenPrinter(sName, hPrinter, IntPtr.Zero) = 0) Then
                Marshal.ThrowExceptionForHR(System.Runtime.InteropServices.Marshal.GetHRForLastWin32Error())
            End If
            Try

                Dim iNeed As Integer = -1

                ' Get the number of bytes needed.
                GetPrinter(hPrinter, 2, IntPtr.Zero, 0, iNeed)

                ' Allocate enough memory.
                pPrinterInfo = Marshal.AllocHGlobal(iNeed)

                Dim SizeOf As Integer = iNeed

                If (GetPrinter(hPrinter, 2, pPrinterInfo, SizeOf, iNeed) = 0) Then
                    Marshal.ThrowExceptionForHR(System.Runtime.InteropServices.Marshal.GetHRForLastWin32Error())
                End If

                ' Now marshal the structure manually.
                'PRINTER_INFO_2 PrinterInfo = (PRINTER_INFO_2) Marshal.PtrToStructure(pPrinterInfo, typeof(PRINTER_INFO_2));
                Dim PrinterInfo As PRINTER_INFO_2 = CType(Marshal.PtrToStructure(pPrinterInfo, GetType(PRINTER_INFO_2)), PRINTER_INFO_2)

                mStatus = PrinterInfo.Status
                mJobs = PrinterInfo.cJobs
                mDriver = PrinterInfo.pDriverName
                mDevice = PrinterInfo.pPrinterName
                mPort = PrinterInfo.pPortName.ToString

                MsgBox(mStatus & " - " & mJobs & " - " & mDriver & " - " & mDevice & " - " & mPort)

            Catch exp As Exception
                'Throw exp
            Finally
                ' Close the printer object.
                ClosePrinter(hPrinter)
                ' Deallocate the memory.
                Marshal.FreeHGlobal(pPrinterInfo)
            End Try

            Return True
        Catch ex As Exception
            'Throw ex
            Return False
        End Try
    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        MsgBox(getPrinterInfo("IATS Brady Commons Printer 1"))

    End Sub
End Class


0
 
LVL 1

Accepted Solution

by:
nconfer earned 2000 total points
ID: 17105170
I have solved the problem! :)  Below is the code for anyone to use in the future.  To use it just create a VB.net application and add one button to the form.  Then go to the code and past all of this code.  You will need to update the printer name in the function call when you click the button to a printer installed on your computer, but other than that, you'll be good to go and be able to get the port name of a printer in VB.NET

Option Strict Off
Option Explicit On

Imports System.Runtime.InteropServices

Public Class Form1

    <DllImport("winspool.drv", EntryPoint:="OpenPrinterW", CharSet:=CharSet.Auto, SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Private Shared Function OpenPrinter(ByVal pPrinterName As String, ByRef hPrinter As IntPtr, ByVal pDefault As IntPtr) As Boolean
    End Function

    <DllImport("winspool.drv", CharSet:=CharSet.Auto, SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Private Shared Function ClosePrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function


    <DllImport("winspool.drv", EntryPoint:="GetPrinterW", CharSet:=CharSet.Auto, SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Private Shared Function GetPrinter(ByVal hPrinter As IntPtr, ByVal dwLevel As Integer, ByVal pPrinter As IntPtr, ByVal cbBuf As Integer, ByRef pcbNeeded As Integer) As Boolean
    End Function

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> Public Structure PRINTER_INFO_2
        Dim pServerName As String
        Dim pPrinterName As String
        Dim pShareName As String
        Dim pPortName As String
        Dim pDriverName As String
        Dim pComment As String
        Dim pLocation As String
        Dim pDevMode As Integer
        Dim pSepFile As String
        Dim pPrintProcessor As String
        Dim pDatatype As String
        Dim pParameters As String
        Dim pSecurityDescriptor As Integer
        Dim Attributes As Integer
        Dim Priority As Integer
        Dim DefaultPriority As Integer
        Dim StartTime As Integer
        Dim UntilTime As Integer
        Dim Status As Integer
        Dim cJobs As Integer
        Dim AveragePPM As Integer
    End Structure

    Private Shared mStatus As Integer
    Private Shared mJobs As Integer
    Private Shared mDriver As String
    Private Shared mDevice As String
    Private Shared mPort As String


    Public Function GetPrinterInfo(ByVal sName As String) As PRINTER_INFO_2
        Try
            Dim hPrinter As IntPtr = IntPtr.Zero
            Dim pPrinterInfo As IntPtr = IntPtr.Zero


            If (Not OpenPrinter(sName, hPrinter, IntPtr.Zero)) Then
                Marshal.ThrowExceptionForHR(System.Runtime.InteropServices.Marshal.GetHRForLastWin32Error())
            End If


            Try
                Dim iNeed As Integer = -1


                ' Get the number of bytes needed.
                GetPrinter(hPrinter, 2, IntPtr.Zero, 0, iNeed)


                ' Allocate enough memory.
                pPrinterInfo = Marshal.AllocHGlobal(iNeed)


                Dim SizeOf As Integer = iNeed


                If (Not GetPrinter(hPrinter, 2, pPrinterInfo, SizeOf, iNeed)) Then
                    Marshal.ThrowExceptionForHR(System.Runtime.InteropServices.Marshal.GetHRForLastWin32Error())
                End If


                ' Now marshal the structure manually.
                Dim PrinterInfo As PRINTER_INFO_2 = CType(Marshal.PtrToStructure(pPrinterInfo, GetType(PRINTER_INFO_2)), PRINTER_INFO_2)

                Return PrinterInfo

            Catch ex As Exception
                'Throw exp
            Finally
                ' Close the printer object.
                ClosePrinter(hPrinter)

                ' Deallocate the memory.
                Marshal.FreeHGlobal(pPrinterInfo)
            End Try
        Catch exp As Exception
            'Throw exp
        End Try
        Return New PRINTER_INFO_2()
    End Function
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim PrinterInformation As PRINTER_INFO_2 = GetPrinterInfo("PUT PRINTER NAME HERE")
        MsgBox(PrinterInformation.pPortName)
    End Sub
End Class
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
Suggested Courses

688 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