tags:

views:

217

answers:

3

I have a VB6 application that needs to recognise when the user changes the Windows Default printer via the Control Panel.

Now when the application starts up, "Printer.DeviceName" contains that default printer name...easy.

If you then change the Windows Default Printer via the control panel, your VB app won't recognize the new default until it is restarted.

Is there any way to refresh the VB Printer object somehow, so your app can recognize the change?

A: 

You could add a Timer object on the Form, with a 10 seconds trigger which checks if the printer has changed.

Manuel Ferreria
Yeh - thanks, but unfortunately VB's Printer object isn't refreshed, so it still tells me that the printer is as it was, when the app started.
Stuart Helwig
+2  A: 

I found a solution. Use API call as follows;

Private Declare Function GetProfileString Lib "kernel32.dll" Alias "GetProfileStringA" (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long) As Long


Public Function GetDefaultPrinter() As Printer

    Dim strBuffer As String * 254
    Dim iRetValue As Long
    Dim strDefaultPrinterInfo As String
    Dim tblDefaultPrinterInfo() As String
    Dim objPrinter As Printer

    ' Retreive current default printer information
    iRetValue = GetProfileString("windows", "device", ",,,", strBuffer, 254)
    strDefaultPrinterInfo = Left(strBuffer, InStr(strBuffer, Chr(0)) - 1)
    tblDefaultPrinterInfo = Split(strDefaultPrinterInfo, ",")
    For Each objPrinter In Printers
        If objPrinter.DeviceName = tblDefaultPrinterInfo(0) Then
            ' Default printer found !
            Exit For
        End If
    Next

    ' If not found, return nothing
    If objPrinter.DeviceName <> tblDefaultPrinterInfo(0) Then
        Set objPrinter = Nothing
    End If

    Set GetDefaultPrinter = objPrinter

End Function

Thanks to http://www.andreavb.com/tip070005.html

Stuart Helwig
+5  A: 

There's an easier way. When your application starts, just set the Printer object's TrackDefault property to True.

Public Sub Main()

    Printer.TrackDefault = True

End Sub

When the TrackDefault property is True, the Printer object will track changes to the default printer made through the Control Panel automatically.

Mike Spross
It's PrintER.TrackDefault. Thanks! Didn't know about that. (Can't edit this but someone who can, please do.)
Stuart Helwig
Nice idea but in my experience it does not work (bug in VB6) see my answer
MarkJ
Oh dear, I wish I could edit my old comments. What I meant to say is that there is a gotcha. If you change any of the Printer settings through the Printer object, it resets Printer.TrackDefault to False. I suppose it's obvious if you think about it. I will go back into my hole now.
MarkJ
A gotcha worth looking out for. Thanks MarkJ
Stuart Helwig