0

I have this Code that adds a Network Printer:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim printerName As String = TextBox1.Text.Trim()

    If String.IsNullOrEmpty(printerName) Then
        MessageBox.Show("Provide a correct Printer Name")
        Return
    End If

    Try
        Dim network As New WshNetwork()
        network.AddWindowsPrinterConnection($"\\ws-print-se\{printerName}")

        If CheckBox1.Checked Then
            SetDefaultPrinter(printerName)
            MessageBox.Show($"The Printer '{printerName}' was installed and set to default.")
        Else
            MessageBox.Show($"The Printer '{printerName}' was installed.")
        End If
    Catch ex As Exception
        MessageBox.Show($"Error during Installation")
    End Try
End Sub
Private Sub SetDefaultPrinter(printerName As String)
    Try
        Dim query As String = $"SELECT * FROM Win32_Printer WHERE Name = '{printerName.Replace("\", "\\")}'"
        Dim searcher As New ManagementObjectSearcher(query)

        For Each printer As ManagementObject In searcher.Get()
            printer.InvokeMethod("SetDefaultPrinter", Nothing)
            MessageBox.Show($"The Printer '{printerName}' was set as default.")
            Return
        Next

        MessageBox.Show($"Error during set as default Printer, Printer wasn't found")
    Catch ex As Exception
        MessageBox.Show($"Error during set as default Printer: {ex.Message}")
    End Try
End Sub

I added a Checkbox to choose if the printer that is gonna be installed is set to default. When not checked, it just installs the printer. When checked (set as default), it installes the printer, then the message "Error during set as default Printer, Printer wasn't found" and then the message "The Printer '{printerName}' was installed and set to default" comes up. But the printer isn't set as default. Any ideas why?

Ajdin
  • 57
  • 3
  • [Selecting specific printer by name](https://stackoverflow.com/a/65946161/7444103) – Jimi Jul 25 '23 at 12:05
  • Turn off ["Let Windows manage my default printer"](https://support.microsoft.com/en-us/windows/set-a-default-printer-in-windows-e10cf8b8-e596-b102-bf84-c41022b5036f) – Hans Passant Jul 25 '23 at 12:33
  • @HansPassant It is turned off – Ajdin Jul 25 '23 at 12:37
  • @Jimi I don't have a button, i have a checkbox which. if checked, should set the printer as default DURING the installation – Ajdin Jul 25 '23 at 12:38
  • I don't see how that matters. That's code you can execute wherever you want. Just verify that `PrinterSettings.InstalledPrinters` (uses [EnumPrinters](https://learn.microsoft.com/en-us/windows/win32/printdocs/enumprinters), both local and connected) acknowledges the presence of the Printer (wait for it with a timeout or, better, have an async methods setup with a timed CancellationToken), then set it as default as described – Jimi Jul 25 '23 at 13:26

0 Answers0