#include once "window9.bi"

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

Function HWNDPrinter(byval hWnd As HWND, _
					byval Xpr As Integer, byval Ypr As Integer, _
					byval X   As Integer, byval Y   As Integer, _
					byval X1  As Integer, byval Y1  As Integer) As integer Export
	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
	End If
	If a.FLY1 > a.FLY2 Then
		a.SCY = a.FLY1 / a.FLY2
	Else
		a.SCY = a.FLY2 / a.FLY1
	End If
	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
	End If
	If Ypr=-1 Then
		a.FLY3 = GetDeviceCaps( a.pd.hDC, VERTRES)
		Ypr=(a.FLY3-Y1*a.SCY)\2
	Else
		Ypr=Ypr*a.SCY
	End If   
	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
