#Include once "window9.bi"

Function HWNDPrinter(hWnd As HWND,Xpr As Integer=0,Ypr As Integer=0,X As Integer=0,_
                     Y As Integer=0,X1 As Integer=0,Y1 As Integer=0) As Long Export

  Type All_
    As Integer result,FLX3,FLY3
    As Single FLX1,FLX2,FLY1,FLY2,SCX,SCY
    As HDC hDC,hDesktopDC
    As PrintDlg pd
    As DOCINFO di
    As RECT R
    As DEVMODE ptr dm
  End Type

  Dim a As ALL_

  a.hDC=GetDC(hwnd)
  GetClientRect(hwnd,@a.R)
  Dim R As RECT
  If X1=0 Then
    X1=a.R.right-a.R.left
  EndIf
  If Y1=0 Then
    Y1=a.R.bottom-a.R.top
  EndIf

  a.pd.lStructSize = SizeOf(PrintDlg)
  a.pd.Flags = PD_RETURNDC
  a.pd.hWndOwner = hWnd
  If PrintDlg(@a.pd)=0 Then Exit Function  

  a.hDesktopDC = GetDC( 0 )
  a.FLX1 = GetDeviceCaps( a.hDesktopDC, LOGPIXELSX )
  a.FLY1 = GetDeviceCaps( a.hDesktopDC, LOGPIXELSY )
  ReleaseDC( 0, a.hDesktopDC )

  a.FLX2 = GetDeviceCaps( a.pd.hDC, LOGPIXELSX )
  a.FLY2 = GetDeviceCaps( a.pd.hDC, LOGPIXELSY )

  If a.FLX1 > a.FLX2 Then
    a.SCX = a.FLX1 / a.FLX2
  Else
    a.SCX = a.FLX2 / a.FLX1
  EndIf
  If a.FLY1 > a.FLY2 Then
    a.SCY = a.FLY1 / a.FLY2
  Else
    a.SCY = a.FLY2 / a.FLY1
  EndIf
  a.dm = GlobalLock( a.pd.hDevMode )
  If Xpr=-1 Then
    a.FLX3 = GetDeviceCaps( a.pd.hDC, HORZRES)
    Xpr=(a.FLX3-X1*a.SCX)\2
  Else
    Xpr=Xpr*a.SCX
  EndIf
  If Ypr=-1 Then
    a.FLY3 = GetDeviceCaps( a.pd.hDC, VERTRES)
    Ypr=(a.FLY3-Y1*a.SCY)\2
  Else
    Ypr=Ypr*a.SCY
  EndIf   
  GlobalUnlock( a.dm )
  For b As Integer =1 To a.pd.nCopies
    If StartDoc (a.pd.hDC, @a.di)>0 Then
      If StartPage (a.pd.hDC)>0 Then
        If StretchBlt(a.pd.hDC,Xpr,Ypr,X1*a.SCX,Y1*a.SCY,a.hdc,X,Y,X1,Y1,SRCCOPY)<=0 Then
          MessageBox(0,"Error StretchBlt! N:  " & GetLastError() ,"Error",0)
        Else
          a.result=1
        EndIf
        EndPage a.pd.hDC        
      EndIf
      EndDoc a.pd.hDC
    EndIf
  Next
  DeleteDC a.pd.hDC :DeleteDC a.hDC
  Return a.result
End Function
