Using PRINTER_DEFAULTS with OpenPrinter fails

  • Thread starter Thread starter active
  • Start date Start date
A

active

Any idea why this fails with an
OpenPrinter exited with code : 5
Message is: Access is denied.

I have Adminstrative rights

Public Structure PRINTER_DEFAULTS
Dim pDatatype As Integer 'String I"VE TRIED BOTH
Dim pDevMode As Integer
Dim DesiredAccess As Integer
End Structure
....snip

PrinterDefaults.pDatatype = 0
PrinterDefaults.pDevMode = 0
PrinterDefaults.DesiredAccess = PRINTER_ALL_ACCESS
ALSO TRIED PRINTER_ACCESS_ADMINISTER
Flag = OpenPrinter(PrinterName, PrinterHandle, PrinterDefaults)

If Flag = 0 Then
ret = Marshal.GetLastWin32Error()
Console.WriteLine("OpenPrinter exited with code : {0}", ret)
Console.WriteLine("Message is: {0}", UtilityCs.GetErrorMessage(ret))
If ret = ERROR_ACCESS_DENIED Then
MsgBox("Requires Adminstrative rights to change default
printer", _
MsgBoxStyle.Exclamation Or MsgBoxStyle.OKOnly)
End If
Exit Sub
End If
 
If you're running win2K and above, try the SetDefaultPrinter function in
winspool.drv:

<DllImport("winspool.drv")> _
Private Shared Function SetDefaultPrinter(ByVal printerName As String) As
Boolean
End Function

Public Shared Sub SetPrinterAsDefault(ByVal PrinterName As String)
If Not SetDefaultPrinter(PrinterName) Then
Throw New Exception("Unable to set printer")
End If
End Sub

Note that the printer name is the printer name, driver, and port, like
what is returned from GetDefaultPrinter or EnumPrinters.
 
Back
Top