GRS

Printing from AutoIt

17 posts in this topic

#1 ·  Posted (edited)

I am somewhat new to AutoIt, but have been trying to create a UDF for printing that does not require a DLL external to the OS.

I have not been able to add the ability to print images or to change the paper orientation. I have only tested this on WinXP with AutoIt v3.2.12.0.
Could someone help add these features(printing images & setting paper orientation)?

PrintWinAPI.au3:

#include-once
#include <WinAPI.au3>

#include <FontConstants.au3>

#include <GDIPlus.au3>

Const $HORZRES = 8

Const $VERTRES = 10

Const $PS_SOLID = 0

Const $PS_DASH = 1

Const $PS_DOT = 2

Const $PS_DASHDOT = 3

Const $PS_DASHDOTDOT = 4

Const $PS_NULL = 5

Const $PS_INSIDEFRAME = 6

Const $AD_COUNTERCLOCKWISE = 1

Const $AD_CLOCKWISE = 2

;=========================================================

Global Const $tagDOCINFO = "int Size;" & _ ; int cbSize;
        
"ptr DocName;" & _ ; LPCTSTR lpszDocName;
        
"ptr Output;" & _ ; LPCTSTR lpszOutput;
        
"ptr Datatype;" & _ ; LPCTSTR lpszDatatype;
        
"dword Type" ; DWORD fwType;

; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_CreateDC



; Description ...: Creates a device context (DC) for a device using the specified name.

; Syntax.........: _WinAPI_CreateDC($sDriver, $sDevice)

; Parameters ....: $sDriver - Specifies driver name, "winspool" for printing, "display" for screen

; $sDevice - Specifies device name

; Return values .: Success - handle to a DC for the specified device

; ====================================================================================================

Func _WinAPI_CreateDC($sDriver, $sDevice)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "hwnd", "CreateDC", "str", $sDriver, "str", $sDevice, "long", 0, "long", 0)

    Return $aResult[0]

EndFunc   ;==>_WinAPI_CreateDC



; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_StartDoc



; Description ...: Starts a print job

; Syntax.........: _WinAPI_StartDoc($hDC, $tDocInfo)

; Parameters ....: $hDC - Identifies the device contex



; $tDocInfo - $tagDOCINFO structure that specifies document info

; Return values .: Success - print job identifier for the document

; ====================================================================================================

Func _WinAPI_StartDoc($hDC, $tDocInfo)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "StartDoc", "hwnd", $hDC, "ptr", DllStructGetPtr($tDocInfo))

    Return $aResult[0]

EndFunc   ;==>_WinAPI_StartDoc



; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_EndDoc



; Description ...: Ends a print job

; Syntax.........: _WinAPI_EndDoc($hDC)

; Parameters ....: $hDC - Identifies the device contex



; Return values .: Success - return value greater than zero

; ====================================================================================================

Func _WinAPI_EndDoc($hDC)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "EndDoc", "hwnd", $hDC)

    Return $aResult[0]

EndFunc   ;==>_WinAPI_EndDoc



; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_StartPage



; Description ...: Prepares the printer driver to accept data

; Syntax.........: _WinAPI_StartPage($hDC)

; Parameters ....: $hDC - Identifies the device contex



; Return values .: Success - return value greater than zero

; ====================================================================================================

Func _WinAPI_StartPage($hDC)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "StartPage", "hwnd", $hDC)

    Return $aResult[0]

EndFunc   ;==>_WinAPI_StartPage



; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_EndPage



; Description ...: Notifies the device that the application has finished writing to a page

; Syntax.........: _WinAPI_EndPage($hDC)

; Parameters ....: $hDC - Identifies the device contex



; Return values .: Success - return value greater than zero

; ====================================================================================================

Func _WinAPI_EndPage($hDC)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "EndPage", "hwnd", $hDC)

    Return $aResult[0]

EndFunc   ;==>_WinAPI_EndPage



; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_TextOut



; Description ...: Writes a character string at the specified location, using the currently selected font, background color, and text color



; Syntax.........: _WinAPI_TextOut($hDC, $iXStart, $iYStart, $sString)

; Parameters ....: $hDC - Identifies the device contex



; $iXStart - x-coordinate of starting position

; $iYStart - y-coordinate of starting position

; $sString - character string

; Return values .: Success - return value is nonzero

; ====================================================================================================


Func _WinAPI_TextOut($hDC, $iXStart, $iYStart, $sString = "")

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "TextOut", "hwnd", $hDC, "long", $iXStart, "long", $iYStart, "str", $sString, "long", StringLen($sString))

    Return $aResult[0]

EndFunc   ;==>_WinAPI_TextOut



; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_CreatePen



; Description ...: Creates a logical pen that has the specified style, width, and color



; Syntax.........: _WinAPI_CreatePen($iPenStyle, $iWidth, $iColor)

; Parameters ....: $iPenStyle - specifies pen style

; $PS_SOLID = 0

; $PS_DASH = 1

; $PS_DOT = 2

; $PS_DASHDOT = 3

; $PS_DASHDOTDOT = 4

; $PS_NULL = 5

; $PS_INSIDEFRAME = 6

; $iWidth - width of the pen

; $iColor - pen color stated in RGB

; Return values .: Success - Handle to logical pen

; ====================================================================================================

Func _WinAPI_CreatePen($iPenStyle = $PS_SOLID, $iWidth = 0, $iColor = 0x000000)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "hwnd", "CreatePen", "int", $iPenStyle, "int", $iWidth, "dword", $iColor)

    Return $aResult[0]

EndFunc   ;==>_WinAPI_CreatePen



; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_MoveToEx



; Description ...: Updates the current position to the specified point and optionally retrieves the previous position

; Syntax.........: _WinAPI_MoveToEx($hDC, $iX, $iY, $tPoint)

; Parameters ....: $hDC - Identifies the device contex



; $iX - x-coordinate of the new position, in logical units

; $iY - y-coordinate of the new position, in logical units

; $tPoint - $tagPOINT structure that receives the previous position

; Return values .: Success - non-zero value

; ====================================================================================================

Func _WinAPI_MoveToEx($hDC, $iX, $iY, ByRef $tPoint)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "MoveToEx", "long", $hDC, "int", $iX, "int", $iY, "ptr", DllStructGetPtr($tPoint))

    Return $aResult[0]

EndFunc   ;==>_WinAPI_MoveToEx



; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_LineTo



; Description ...: Draws a line from the current position up to, but not including, the specified point

; Syntax.........: _WinAPI_LineTo($hDC, $iXEnd, $iYEnd)

; Parameters ....: $hDC - Identifies the device contex



; $iXEnd - x-coordinate, in logical units, of the endpoint of the line

; $iYEnd - y-coordinate, in logical units, of the endpoint of the line

; Return values .: Success - non-zero value

; ====================================================================================================

Func _WinAPI_LineTo($hDC, $iXEnd, $iYEnd)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "LineTo", "long", $hDC, "int", $iXEnd, "int", $iYEnd)

    Return $aResult[0]

EndFunc   ;==>_WinAPI_LineTo



; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_SetArcDirection



; Description ...: Sets the drawing direction to be used for arc and rectangle functions

; Syntax.........: _WinAPI_SetArcDirection($hDC, $Direction)

; Parameters ....: $hDC - Identifies the device contex



; $Direction - Specifies the new arc direction

; $AD_COUNTERCLOCKWISE = 1

; $AD_CLOCKWISE = 2

; Return values .: Success - old arc direction

; ====================================================================================================

Func _WinAPI_SetArcDirection($hDC, $Direction)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "SetArcDirection", "long", $hDC, "int", $Direction)

    Return $aResult[0]

EndFunc   ;==>_WinAPI_SetArcDirection



; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_ArcTo



; Description ...: Draws an elliptical arc

; Syntax.........: _WinAPI_ArcTo($hDC, $iLeftRect, $iTopRect, $iRightRect, $iBottomRect, $iXRadial1, $iYRadial1, $iXRadial2, $iYRadial2)

; Parameters ....: $hDC - Identifies the device contex



; $iLeftRect - x-coord of rectangle's upper-left corner

; $iTopRect - y-coord of rectangle's upper-left corner

; $iRightRect - x-coord of rectangle's lower-right corner

; $iBottomRect - y-coord of rectangle's lower-right corner

; $iXRadial1 - x-coord of first radial ending point

; $iYRadial1 - y-coord of first radial ending point

; $iXRadial2 - x-coord of second radial ending point

; $iYRadial2 - y-coord of second radial ending point

; Return values .: Success - return value is nonzero

; ====================================================================================================

Func _WinAPI_ArcTo($hDC, $iLeftRect, $iTopRect, $iRightRect, $iBottomRect, $iXRadial1, $iYRadial1, $iXRadial2, $iYRadial2)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "ArcTo", "long", $hDC, "int", $iLeftRect, "int", $iTopRect, "int", $iRightRect, "int", $iBottomRect, "int", $iXRadial1, "int", $iYRadial1, "int", $iXRadial2, "int", $iYRadial2)

    Return $aResult[0]

EndFunc   ;==>_WinAPI_ArcTo



; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_Arc

; Description ...: Draws an elliptical arc

; Syntax.........: _WinAPI_Arc($hDC, $iLeftRect, $iTopRect, $iRightRect, $iBottomRect, $iXStartArc, $iYStartArc, $iXEndArc, $iYEndArc)

; Parameters ....: $hDC - Identifies the device contex



; $iLeftRect - x-coord of rectangle's upper-left corner

; $iTopRect - y-coord of rectangle's upper-left corner

; $iRightRect - x-coord of rectangle's lower-right corner

; $iBottomRect - y-coord of rectangle's lower-right corner

; $iXStartArc - x-coord of first radial ending point

; $iYStartArc - y-coord of first radial ending point

; $iXEndArc - x-coord of second radial ending point

; $iYEndArc - y-coord of second radial ending point

; Return values .: Success - return value is nonzero

; ====================================================================================================

Func _WinAPI_Arc($hDC, $iLeftRect, $iTopRect, $iRightRect, $iBottomRect, $iXStartArc, $iYStartArc, $iXEndArc, $iYEndArc)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "Arc", "long", $hDC, "int", $iLeftRect, "int", $iTopRect, "int", $iRightRect, "int", $iBottomRect, "int", $iXStartArc, "int", $iYStartArc, "int", $iXEndArc, "int", $iYEndArc)

    Return $aResult[0]

EndFunc   ;==>_WinAPI_Arc

; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_Rectangle

; Description ...: Draws a rectangle

; Syntax.........: _WinAPI_Rectangle($hDC, $iLeftRect, $iTopRect, $iRightRect, $iBottomRect)

; Parameters ....: $hDC - Identifies the device contex



; $iLeftRect - x-coord of rectangle's upper-left corner

; $iTopRect - y-coord of rectangle's upper-left corner

; $iRightRect - x-coord of rectangle's lower-right corner

; $iBottomRect - y-coord of rectangle's lower-right corner

; Return values .: Success - return value is nonzero

; ====================================================================================================

Func _WinAPI_Rectangle($hDC, $iLeftRect, $iTopRect, $iRightRect, $iBottomRect)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "Rectangle", "long", $hDC, "int", $iLeftRect, "int", $iTopRect, "int", $iRightRect, "int", $iBottomRect)

    Return $aResult[0]

EndFunc   ;==>_WinAPI_Rectangle

; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_RoundRect



; Description ...: Draws a rectangle

; Syntax.........: _WinAPI_RoundRect($hDC, $iLeftRect, $iTopRect, $iRightRect, $iBottomRect, $iWidth, $iHeight)

; Parameters ....: $hDC - Identifies the device contex



; $iLeftRect - x-coord of rectangle's upper-left corner

; $iTopRect - y-coord of rectangle's upper-left corner

; $iRightRect - x-coord of rectangle's lower-right corner

; $iBottomRect - y-coord of rectangle's lower-right corner

; $iWidth - width of ellipse

; $iHeight - height of ellipse

; Return values .: Success - return value is nonzero

; ====================================================================================================

Func _WinAPI_RoundRect($hDC, $iLeftRect, $iTopRect, $iRightRect, $iBottomRect, $iWidth, $iHeight)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "RoundRect", "long", $hDC, "int", $iLeftRect, "int", $iTopRect, "int", $iRightRect, "int", $iBottomRect, "int", $iWidth, "int", $iHeight)

    Return $aResult[0]

EndFunc   ;==>_WinAPI_RoundRect



; #FUNCTION# ====================================================================================================

; Name...........: _WinAPI_Ellipse

; Description ...: Draws a ellipse

; Syntax.........: _WinAPI_Ellipse($hDC, $iLeftRect, $iTopRect, $iRightRect, $iBottomRect)

; Parameters ....: $hDC - Identifies the device contex



; $iLeftRect - x-coord of rectangle's upper-left corner of rectangle

; $iTopRect - y-coord of rectangle's upper-left corner of rectangle

; $iRightRect - x-coord of rectangle's lower-right corner of rectangle

; $iBottomRect - y-coord of rectangle's lower-right corner of rectangle

; Return values .: Success - return value is nonzero

; ====================================================================================================

Func _WinAPI_Ellipse($hDC, $iLeftRect, $iTopRect, $iRightRect, $iBottomRect)

    Local $aResult



    $aResult = DllCall("GDI32.dll", "long", "Ellipse", "long", $hDC, "int", $iLeftRect, "int", $iTopRect, "int", $iRightRect, "int", $iBottomRect)

    Return $aResult[0]

EndFunc   ;==>_WinAPI_Ellipse

Sample output:

post-36800-1213804959_thumb.jpg

Example.au3

#include <PrintWinAPI.au3>

; Create a printer device context

$s_DefaultPrinter = _GetDefaultPrinter()

$s_PrinterName = InputBox("AutoIt API Printing", "Enter printer name", $s_DefaultPrinter)

If $s_PrinterName = "" Then Exit

$hPrintDc = _WinAPI_CreateDC("winspool", $s_PrinterName)

; get pixel and twips info

$PixelsPerInchY = _WinAPI_GetDeviceCaps($hPrintDc, $__WINAPCONSTANT_LOGPIXELSY) ; Get Pixels Per Inch Y

$TwipsPerPixelY = 1440 / $PixelsPerInchY

$PixelsPerInchX = _WinAPI_GetDeviceCaps($hPrintDc, $__WINAPCONSTANT_LOGPIXELSX) ; Get Pixels Per Inch X

$TwipsPerPixelX = 1440 / $PixelsPerInchX

; get page width and height

$PageWidth = _WinAPI_GetDeviceCaps($hPrintDc, $HORZRES) ; Get width, in millimeters, of the physical screen

$PageHeight = _WinAPI_GetDeviceCaps($hPrintDc, $VERTRES) ; Get height, in millimeters, of the physical screen.

; set docinfo

$s_DocName = "Printing from AutoIt with WinAPI"

$DocName = DllStructCreate("char DocName[" & StringLen($s_DocName & Chr(0)) & "]")

DllStructSetData($DocName, "DocName", $s_DocName & Chr(0)) ; Size of DOCINFO structure

$DOCINFO = DllStructCreate($tagDOCINFO) ; Structure for Print Document info

DllStructSetData($DOCINFO, "Size", 20) ; Size of DOCINFO structure

DllStructSetData($DOCINFO, "DocName", DllStructGetPtr($DocName)) ; Set name of print job (Optional)

; start new print doc

$result = _WinAPI_StartDoc($hPrintDc, $DOCINFO)

; start new page

$result = _WinAPI_StartPage($hPrintDc)

; create font

$DESIREDFONTSIZE = 16

$hFont = _WinAPI_CreateFont((($DESIREDFONTSIZE * -20) / $TwipsPerPixelY), 0, 0, 0, $FW_NORMAL, True, True, False _
        
, $DEFAULT_CHARSET, $OUT_DEFAULT_PRECIS, $CLIP_DEFAULT_PRECIS, $DEFAULT_QUALITY, $DEFAULT_PITCH, 'Verdona')

; set newfond, save old font

$hFontOld = _WinAPI_SelectObject($hPrintDc, $hFont)

; print centered test message

$s_TextOut = "This is a test..."

$OutSize = _WinAPI_GetTextExtentPoint32($hPrintDc, $s_TextOut)

; Compute the starting point for the text-output operation(centered)

$xLeft = (($PageWidth / 2) - (DllStructGetData($OutSize, "X") / 2))

; Compute the starting point for the text-output 2 lines down

$yTop = DllStructGetData($OutSize, "Y") * 2

; Send text

$result = _WinAPI_TextOut($hPrintDc, $xLeft, $yTop, $s_TextOut)

; create font structure, rotated 180 degrees

$lf = DllStructCreate($tagLOGFONT)

$DESIREDFONTSIZE = 12

DllStructSetData($lf, "Escapement", 2700)

DllStructSetData($lf, "Height", (($DESIREDFONTSIZE * -20) / $TwipsPerPixelY))

DllStructSetData($lf, "Italic", False)

DllStructSetData($lf, "Underline", False)

DllStructSetData($lf, "FaceName", "Arial")

; set font

$hLF = _WinAPI_CreateFontIndirect($lf)

$result = _WinAPI_SelectObject($hPrintDc, $hLF)

; Send rotated text to printer, starting at location 1000, 1000

$xLeft = 1000

$yTop = 1000

$s_TextOut = "Testing...123"

$result = _WinAPI_TextOut($hPrintDc, $xLeft, $yTop, $s_TextOut)

; update font

_WinAPI_DeleteObject($hLF)

DllStructSetData($lf, "Escapement", 2250)

$hLF = _WinAPI_CreateFontIndirect($lf)

$result = _WinAPI_SelectObject($hPrintDc, $hLF)

; Send rotated text to printer, starting at location 1000, 1000

$result = _WinAPI_TextOut($hPrintDc, $xLeft, $yTop, $s_TextOut)

; update font

_WinAPI_DeleteObject($hLF)

$hLF = _WinAPI_CreateFont((($DESIREDFONTSIZE * -20) / $TwipsPerPixelY), 0, 1800, 0, $FW_NORMAL, False, False, False _
        
, $DEFAULT_CHARSET, $OUT_DEFAULT_PRECIS, $CLIP_DEFAULT_PRECIS, $DEFAULT_QUALITY, $DEFAULT_PITCH, 'Arial')

$result = _WinAPI_SelectObject($hPrintDc, $hLF)

; Send rotated text to printer, starting at location 1000, 1000

$result = _WinAPI_TextOut($hPrintDc, $xLeft, $yTop, $s_TextOut)

; update font

_WinAPI_DeleteObject($hLF)

$hLF = _WinAPI_CreateFont((($DESIREDFONTSIZE * -20) / $TwipsPerPixelY), 0, 1500, 0, $FW_NORMAL, False, False, False _
        
, $DEFAULT_CHARSET, $OUT_DEFAULT_PRECIS, $CLIP_DEFAULT_PRECIS, $DEFAULT_QUALITY, $DEFAULT_PITCH, 'Arial')

$result = _WinAPI_SelectObject($hPrintDc, $hLF)

; Send rotated text to printer, starting at location 1000, 1000

$result = _WinAPI_TextOut($hPrintDc, $xLeft, $yTop, $s_TextOut)

; update font

_WinAPI_DeleteObject($hLF)

$hLF = _WinAPI_CreateFont((($DESIREDFONTSIZE * -20) / $TwipsPerPixelY), 0, 1200, 0, $FW_NORMAL, False, False, False _
        
, $DEFAULT_CHARSET, $OUT_DEFAULT_PRECIS, $CLIP_DEFAULT_PRECIS, $DEFAULT_QUALITY, $DEFAULT_PITCH, 'Arial')

$result = _WinAPI_SelectObject($hPrintDc, $hLF)

; Send rotated text to printer, starting at location 1000, 1000

$result = _WinAPI_TextOut($hPrintDc, $xLeft, $yTop, $s_TextOut)

; update font

_WinAPI_DeleteObject($hLF)

$hLF = _WinAPI_CreateFont((($DESIREDFONTSIZE * -20) / $TwipsPerPixelY), 0, 900, 0, $FW_NORMAL, False, False, False _
        
, $DEFAULT_CHARSET, $OUT_DEFAULT_PRECIS, $CLIP_DEFAULT_PRECIS, $DEFAULT_QUALITY, $DEFAULT_PITCH, 'Arial')

$result = _WinAPI_SelectObject($hPrintDc, $hLF)

; set textcolor, save last textcolor

$iColorOld = _WinAPI_SetTextColor($hPrintDc, 0xFF0000)

; Send rotated text to printer, starting at location 1000, 1000

$result = _WinAPI_TextOut($hPrintDc, $xLeft, $yTop, $s_TextOut)

; update font

_WinAPI_DeleteObject($hLF)

$hLF = _WinAPI_CreateFont((($DESIREDFONTSIZE * -20) / $TwipsPerPixelY), 0, 600, 0, $FW_NORMAL, False, False, False _
        
, $DEFAULT_CHARSET, $OUT_DEFAULT_PRECIS, $CLIP_DEFAULT_PRECIS, $DEFAULT_QUALITY, $DEFAULT_PITCH, 'Arial')

$result = _WinAPI_SelectObject($hPrintDc, $hLF)

; set textcolor, save last textcolor

$result = _WinAPI_SetTextColor($hPrintDc, 0x00FF00)

; Send rotated text to printer, starting at location 1000, 1000

$result = _WinAPI_TextOut($hPrintDc, $xLeft, $yTop, $s_TextOut)

; update font

_WinAPI_DeleteObject($hLF)

$hLF = _WinAPI_CreateFont((($DESIREDFONTSIZE * -20) / $TwipsPerPixelY), 0, 300, 0, $FW_NORMAL, False, False, False _
        
, $DEFAULT_CHARSET, $OUT_DEFAULT_PRECIS, $CLIP_DEFAULT_PRECIS, $DEFAULT_QUALITY, $DEFAULT_PITCH, 'Arial')

$result = _WinAPI_SelectObject($hPrintDc, $hLF)

; set textcolor, save last textcolor

$result = _WinAPI_SetTextColor($hPrintDc, 0x0000FF)

; Send rotated text to printer, starting at location 1000, 1000

$result = _WinAPI_TextOut($hPrintDc, $xLeft, $yTop, $s_TextOut)

; update font

_WinAPI_DeleteObject($hLF)

$hLF = _WinAPI_CreateFont((($DESIREDFONTSIZE * -20) / $TwipsPerPixelY), 0, 0, 0, $FW_BOLD, False, False, False _
        
, $DEFAULT_CHARSET, $OUT_DEFAULT_PRECIS, $CLIP_DEFAULT_PRECIS, $DEFAULT_QUALITY, $DEFAULT_PITCH, 'Arial')

$result = _WinAPI_SelectObject($hPrintDc, $hLF)

; set textcolor, save last textcolor

$result = _WinAPI_SetTextColor($hPrintDc, 0x0)

; Send rotated text to printer, starting at location 1000, 1000

$result = _WinAPI_TextOut($hPrintDc, $xLeft, $yTop, $s_TextOut)

; set textcolor

$result = _WinAPI_SetTextColor($hPrintDc, 0x0000FF)

; restore original font

$result = _WinAPI_SelectObject($hPrintDc, $hFontOld)

; restore original color

$result = _WinAPI_SetTextColor($hPrintDc, $iColorOld)

; delete fonts

_WinAPI_DeleteObject($hFont)

_WinAPI_DeleteObject($hLF)

; create pens to draw with (PenStyle, Width, RGB-Color)

$hPen0 = _WinAPI_CreatePen($PS_SOLID, 0, 0x000000)

$hPen1 = _WinAPI_CreatePen($PS_DASH, 0, 0x000000)

$hPen2 = _WinAPI_CreatePen($PS_DOT, 0, 0x000000)

$hPen3 = _WinAPI_CreatePen($PS_DASHDOT, 0, 0x000000)

$hPen4 = _WinAPI_CreatePen($PS_DASHDOTDOT, 0, 0x000000)

$hPen5 = _WinAPI_CreatePen($PS_SOLID, 20, 0x000000)

$hPen6 = _WinAPI_CreatePen($PS_SOLID, 40, 0x000000)

$hPen7 = _WinAPI_CreatePen($PS_SOLID, 40, 0x0000FF)

$hPen8 = _WinAPI_CreatePen($PS_SOLID, 40, 0x00FF00)

$hPen9 = _WinAPI_CreatePen($PS_SOLID, 40, 0xFF0000)

; set starting point

$LastPoint = DllStructCreate($tagPOINT)

$result = _WinAPI_MoveToEx($hPrintDc, 1000, 2000, $LastPoint)

; select pen, save old pen

$hPenOld = _WinAPI_SelectObject($hPrintDc, $hPen2)

; draw line

$result = _WinAPI_LineTo($hPrintDc, 1100, 3000)

; select pen

$result = _WinAPI_SelectObject($hPrintDc, $hPen4)

; draw line

$result = _WinAPI_LineTo($hPrintDc, 1200, 2000)

; select pen

$result = _WinAPI_SelectObject($hPrintDc, $hPen3)

; draw line

$result = _WinAPI_LineTo($hPrintDc, 1300, 3000)

; select pen

$result = _WinAPI_SelectObject($hPrintDc, $hPen1)

; draw line

$result = _WinAPI_LineTo($hPrintDc, 1400, 2000)

; select pen

$result = _WinAPI_SelectObject($hPrintDc, $hPen0)

; draw line

$result = _WinAPI_LineTo($hPrintDc, 1500, 3000)

; select pen

$result = _WinAPI_SelectObject($hPrintDc, $hPen5)

; draw line

$result = _WinAPI_LineTo($hPrintDc, 1600, 2000)

; select pen

$result = _WinAPI_SelectObject($hPrintDc, $hPen6)

; draw line

$result = _WinAPI_LineTo($hPrintDc, 1700, 3000)

; select pen

$result = _WinAPI_SelectObject($hPrintDc, $hPen7)

; draw line

$result = _WinAPI_LineTo($hPrintDc, 1800, 2000)

; select pen

$result = _WinAPI_SelectObject($hPrintDc, $hPen8)

; draw line

$result = _WinAPI_LineTo($hPrintDc, 1900, 3000)

; select pen

$result = _WinAPI_SelectObject($hPrintDc, $hPen9)

; draw line

$result = _WinAPI_LineTo($hPrintDc, 2000, 2000)

; draw arch connected from current point

$result = _WinAPI_SetArcDirection($hPrintDc, $AD_CLOCKWISE)

$result = _WinAPI_ArcTo($hPrintDc, 2500, 2000, 3000, 2500, 2500, 2500, 3000, 2500)

; select pen

$result = _WinAPI_SelectObject($hPrintDc, $hPen4)

; draw arch

$result = _WinAPI_Arc($hPrintDc, 2500, 1000, 3500, 1500, 0, 0, 0, 0)

; select pen

$result = _WinAPI_SelectObject($hPrintDc, $hPen5)

; create brush

$hBrush = _WinAPI_CreateSolidBrush(0x0000FF)

; select brush

$hBrushOld = _WinAPI_SelectObject($hPrintDc, $hBrush)

; draw rectangles

$result = _WinAPI_Rectangle($hPrintDc, 3500, 2000, 4500, 2500)

$result = _WinAPI_RoundRect($hPrintDc, 3500, 2600, 4500, 3100, 200, 200)

; draw circle

$result = _WinAPI_Ellipse($hPrintDc, 3300, 1800, 3700, 2200)

; restore original brush

$result = _WinAPI_SelectObject($hPrintDc, $hBrushOld)

; select pen

$result = _WinAPI_SelectObject($hPrintDc, $hPen2)

$result = _WinAPI_Arc($hPrintDc, 3300, 1900, 3700, 2300, 0, 0, 0, 0)

; End the page

$result = _WinAPI_EndPage($hPrintDc)

; start new page

$result = _WinAPI_StartPage($hPrintDc)

; print centered test message

$s_TextOut = "This is page 2"

$OutSize = _WinAPI_GetTextExtentPoint32($hPrintDc, $s_TextOut)

; Compute the starting point for the text-output operation(centered)

$xLeft = (($PageWidth / 2) - (DllStructGetData($OutSize, "X") / 2))

; Compute the starting point for the text-output 2 lines down

$yTop = DllStructGetData($OutSize, "Y") * 2

; Send text

$result = _WinAPI_TextOut($hPrintDc, $xLeft, $yTop, $s_TextOut)

; delete pens

_WinAPI_DeleteObject($hPen0)

_WinAPI_DeleteObject($hPen1)

_WinAPI_DeleteObject($hPen2)

_WinAPI_DeleteObject($hPen3)

_WinAPI_DeleteObject($hPen4)

_WinAPI_DeleteObject($hPen5)

_WinAPI_DeleteObject($hPen6)

_WinAPI_DeleteObject($hPen7)

_WinAPI_DeleteObject($hPen8)

_WinAPI_DeleteObject($hPen9)

; delete brush

_WinAPI_DeleteObject($hBrush)

; restore original pen

$result = _WinAPI_SelectObject($hPrintDc, $hPenOld)

; restore original brush

$result = _WinAPI_SelectObject($hPrintDc, $hBrushOld)

; End the page

$result = _WinAPI_EndPage($hPrintDc)

; End the print job

$result = _WinAPI_EndDoc($hPrintDc)

; Delete the printer device context

_WinAPI_DeleteDC($hPrintDc)

Func _GetDefaultPrinter()

    $s_TempDeviceID = ""

    If @OSType = "WIN32_NT" Then

        Local $objWMIService = ObjGet("winmgmts:\\.\root\CIMV2")

        If Not @error = 0 Then

            ; error

        Else

            Local $wbemFlagReturnImmediately = 0x10

            Local $wbemFlagForwardOnly = 0x20

            Local $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_Printer", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)

            If IsObj($colItems) Then

                For $objItem In $colItems

                    If $s_TempDeviceID = "" Then $s_TempDeviceID = $objItem.DeviceID

                    If $objItem.Default Then $s_TempDeviceID = $objItem.DeviceID

                Next

            Else

                ;Msgbox(262192,"WMI Output","No WMI Objects Found for class: " & "Win32_Printer" )

            EndIf

        EndIf

    EndIf

    Return $s_TempDeviceID

EndFunc   ;==>_GetDefaultPrinter

 

 

Edited by Melba23
Fixed formatting
1 person likes this

Share this post


Link to post
Share on other sites



GRS this looks like an excellent start to a true AutoIt printing udf which would be a great contribution IMO. I hope that you will soon be able to replace my udf and dll and I look forward to seeing your results in Example scripts.

I don't know the answers to your questions but when I get some time I will see if I can help you at all with something, though at your present rate I suspect you will stay ahead of me.

What version of AutoIt are you using? I couldn't get your example to run and I guess it's because I'm not using the latest releases.


Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.

Share this post


Link to post
Share on other sites

What version of AutoIt are you using? I couldn't get your example to run and I guess it's because I'm not using the latest releases.

Thanks martin. I am running AutoIt version 3.2.12.0, but that was not the only problem.

:) Some how the code in my original post had some strange formating that broke the UDF. I have edited the original post and now it looks correct if you want to give it another try.

Share this post


Link to post
Share on other sites

Looks very promising!! :)

I think there is no need to make another painting functions as they are already in WinAPI,GDI UDFs.

They are general because they use DC as input and you only give them printer DC instead of graphic DC - it's clever.

Idea: Add printer related functions

- get list of installed printers

- get active printer

- set active printer

Maybe they are already somewhere on the forum...

Share this post


Link to post
Share on other sites

Looks very promising!! :)

I think there is no need to make another painting functions as they are already in WinAPI,GDI UDFs.

They are general because they use DC as input and you only give them printer DC instead of graphic DC - it's clever.

Idea: Add printer related functions

- get list of installed printers

- get active printer

- set active printer

Maybe they are already somewhere on the forum...

This script I wrote here does those things.

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.

Share this post


Link to post
Share on other sites

Very Nice GRS!!!

8)


NEWHeader1.png

Share this post


Link to post
Share on other sites

I moved this topic to Example Scripts so maybe ya'll would feel impelled to help make a nice working .au3 out of it (and of course help with any issue the OP is having).


Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Share this post


Link to post
Share on other sites

Hi GRS! Amazing work there. I've managed to add a function that will print pictures given the printer device context and the file name, and can print them towards the top-left corner, centered, or fitted to the printed page. I do have a couple questions though. First, I would like to use your printwinapi functions in a couple commercial programs and in an auto-it library that may eventually become part of the autoit UDFs, and I was wondering if that would be okay with you. Second, is there any way that you could make the getDefaultPrinter function to work for a 64-bit OS? So far, I think everything else in your code might work with a 64 bit system, but as I don't know anyone who has one, I can't say for sure.

Third, it looks like you used COM objects in your getDefaultPrinter function and you have lines of code like

ObjGet("winmgmts:\\.\root\CIMV2"), and

$objWMIService.ExecQuery("SELECT * FROM Win32_Printer", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)

and I was wondering how you wrote that code, like where did you find winmgmts:\\.\root\CIMV2? I know that MSDN is the place to go to for dlls, but I don't really know anything about COM objects, and I would like to learn.

Well, here's my code to print pictures:

CODE
Func PrintImage($hDC, $filename, $centered = true, $fitToPage = false)

$dll = DllOpen("GDIPlus.dll")

Local $tInput = DllStructCreate("int Version;int Callback;int NoThread;int NoCodecs")

Local $tToken = DllStructCreate("int Data")

DllStructSetData($tInput, "Version", 1)

DllCall($dll, "int", "GdiplusStartup", "ptr", DllStructGetPtr($tToken), "ptr", DllStructGetPtr($tInput), "ptr", 0)

Local $image = DllCall($dll, "int", "GdipLoadImageFromFile", "wstr", $filename, "int*", 0)

Local $imageheight = DllCall($dll, "int", "GdipGetImageHeight", "hwnd", $image[2], "int*", 0)

Local $imagewidth = DllCall($dll, "int", "GdipGetImageWidth", "hwnd", $image[2], "int*", 0)

Local $go = DllCall($dll, "int", "GdipCreateFromHDC", "hwnd", $hDC, "int*", 0)

If $fitToPage OR $centered Then

$tempWin = GUICreate("Test", 200, 200)

$screenHDC = DllCall("user32.dll", "int", "GetDC", "hwnd", $tempWin)

;get monitor pixels per inch

$ppiHeight = _WinAPI_GetDeviceCaps($screenHDC[0], $__WINAPCONSTANT_LOGPIXELSY)

$ppiWidth = _WinAPI_GetDeviceCaps($screenHDC[0], $__WINAPCONSTANT_LOGPIXELSX)

;get printer dots per inch

$dpiHeight = _WinAPI_GetDeviceCaps($hDC, $__WINAPCONSTANT_LOGPIXELSY)

$dpiWidth = _WinAPI_GetDeviceCaps($hDC, $__WINAPCONSTANT_LOGPIXELSX)

;get printer page width and height in dots

$dotsHeight = _WinAPI_GetDeviceCaps($hDC, $VERTRES)

$dotsWidth = _WinAPI_GetDeviceCaps($hDC, $HORZRES)

;get printer page width and height in pixels

$height = $dotsHeight * $ppiHeight / $dpiHeight

$width = $dotsWidth * $ppiWidth / $dpiWidth

DllCall("user32.dll", "int", "ReleaseDC", "hwnd", $tempWin, "int", $screenHDC[0])

GUIDelete($tempWin)

If $fitToPage Then

If ($height/$imageHeight[2]) < ($width/$imageWidth[2]) Then

Local $ratio = $height/$imageHeight[2]

Else

Local $ratio = $width/$imageWidth[2]

EndIf

Local $x = Abs($width - $ratio * $imageWidth[2])/2

Local $y = Abs($height - $ratio * $imageHeight[2])/2

DllCall($dll, "int", "GdipDrawImageRectI", "hwnd", $go[2], "hwnd", $image[2], "int", $x, "int", $y, "int", Round($ratio * $imageWidth[2]), "int", Round($ratio * $imageHeight[2]))

Else

Local $xPos = Abs($width - $imagewidth[2])/2

Local $yPos = Abs($height - $imageHeight[2])/2

DllCall($dll, "int", "GdipDrawImageRectI", "hwnd", $go[2], "hwnd", $image[2], "int", $xPos, "int", $yPos, "int", $imagewidth[2], "int", $imageheight[2])

EndIf

Else

DllCall($dll, "int", "GdipDrawImageRectI", "hwnd", $go[2], "hwnd", $image[2], "int", 0, "int", 0, "int", $imagewidth[2], "int", $imageheight[2])

EndIf

DllCall($dll, "int", "GdipDeleteGraphics", "hwnd", $go[2])

DllCall($dll, "int", "GdipDisposeImage", "hwnd", $image[2])

DllCall($dll, "none", "GdiplusShutdown", "ptr", 0)

DllClose($dll)

EndFunc

Share this post


Link to post
Share on other sites

Hi GRS! Amazing work there. I've managed to add a function that will print pictures given the printer device context and the file name, and can print them towards the top-left corner, centered, or fitted to the printed page. I do have a couple questions though. First, I would like to use your printwinapi functions in a couple commercial programs and in an auto-it library that may eventually become part of the autoit UDFs, and I was wondering if that would be okay with you. Second, is there any way that you could make the getDefaultPrinter function to work for a 64-bit OS? So far, I think everything else in your code might work with a 64 bit system, but as I don't know anyone who has one, I can't say for sure.

Third, it looks like you used COM objects in your getDefaultPrinter function and you have lines of code like

ObjGet("winmgmts:\\.\root\CIMV2"), and

$objWMIService.ExecQuery("SELECT * FROM Win32_Printer", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)

and I was wondering how you wrote that code, like where did you find winmgmts:\\.\root\CIMV2? I know that MSDN is the place to go to for dlls, but I don't really know anything about COM objects, and I would like to learn.

Well, here's my code to print pictures:

CODE
Func PrintImage($hDC, $filename, $centered = true, $fitToPage = false)

$dll = DllOpen("GDIPlus.dll")

Local $tInput = DllStructCreate("int Version;int Callback;int NoThread;int NoCodecs")

Local $tToken = DllStructCreate("int Data")

DllStructSetData($tInput, "Version", 1)

DllCall($dll, "int", "GdiplusStartup", "ptr", DllStructGetPtr($tToken), "ptr", DllStructGetPtr($tInput), "ptr", 0)

Local $image = DllCall($dll, "int", "GdipLoadImageFromFile", "wstr", $filename, "int*", 0)

Local $imageheight = DllCall($dll, "int", "GdipGetImageHeight", "hwnd", $image[2], "int*", 0)

Local $imagewidth = DllCall($dll, "int", "GdipGetImageWidth", "hwnd", $image[2], "int*", 0)

Local $go = DllCall($dll, "int", "GdipCreateFromHDC", "hwnd", $hDC, "int*", 0)

If $fitToPage OR $centered Then

$tempWin = GUICreate("Test", 200, 200)

$screenHDC = DllCall("user32.dll", "int", "GetDC", "hwnd", $tempWin)

;get monitor pixels per inch

$ppiHeight = _WinAPI_GetDeviceCaps($screenHDC[0], $__WINAPCONSTANT_LOGPIXELSY)

$ppiWidth = _WinAPI_GetDeviceCaps($screenHDC[0], $__WINAPCONSTANT_LOGPIXELSX)

;get printer dots per inch

$dpiHeight = _WinAPI_GetDeviceCaps($hDC, $__WINAPCONSTANT_LOGPIXELSY)

$dpiWidth = _WinAPI_GetDeviceCaps($hDC, $__WINAPCONSTANT_LOGPIXELSX)

;get printer page width and height in dots

$dotsHeight = _WinAPI_GetDeviceCaps($hDC, $VERTRES)

$dotsWidth = _WinAPI_GetDeviceCaps($hDC, $HORZRES)

;get printer page width and height in pixels

$height = $dotsHeight * $ppiHeight / $dpiHeight

$width = $dotsWidth * $ppiWidth / $dpiWidth

DllCall("user32.dll", "int", "ReleaseDC", "hwnd", $tempWin, "int", $screenHDC[0])

GUIDelete($tempWin)

If $fitToPage Then

If ($height/$imageHeight[2]) < ($width/$imageWidth[2]) Then

Local $ratio = $height/$imageHeight[2]

Else

Local $ratio = $width/$imageWidth[2]

EndIf

Local $x = Abs($width - $ratio * $imageWidth[2])/2

Local $y = Abs($height - $ratio * $imageHeight[2])/2

DllCall($dll, "int", "GdipDrawImageRectI", "hwnd", $go[2], "hwnd", $image[2], "int", $x, "int", $y, "int", Round($ratio * $imageWidth[2]), "int", Round($ratio * $imageHeight[2]))

Else

Local $xPos = Abs($width - $imagewidth[2])/2

Local $yPos = Abs($height - $imageHeight[2])/2

DllCall($dll, "int", "GdipDrawImageRectI", "hwnd", $go[2], "hwnd", $image[2], "int", $xPos, "int", $yPos, "int", $imagewidth[2], "int", $imageheight[2])

EndIf

Else

DllCall($dll, "int", "GdipDrawImageRectI", "hwnd", $go[2], "hwnd", $image[2], "int", 0, "int", 0, "int", $imagewidth[2], "int", $imageheight[2])

EndIf

DllCall($dll, "int", "GdipDeleteGraphics", "hwnd", $go[2])

DllCall($dll, "int", "GdipDisposeImage", "hwnd", $image[2])

DllCall($dll, "none", "GdiplusShutdown", "ptr", 0)

DllClose($dll)

EndFunc

Maybe one of the methods here would get the default printer ok for you.

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

A small example using some GDI examples from the help pasted into a cut-down version of GRS's example, just to show that GDI can be used with a printer using this udf.

#Include <PrintWinAPI.au3>
#include <ScreenCapture.au3>

; Create a printer device context
$s_DefaultPrinter = _GetDefaultPrinter()
$s_PrinterName = InputBox("AutoIt API Printing", "Enter printer name", $s_DefaultPrinter)
If $s_PrinterName = "" Then Exit
$hPrintDc = _WinAPI_CreateDC("winspool", $s_PrinterName)

; get pixel and twips info
$PixelsPerInchY = _WinAPI_GetDeviceCaps($hPrintDc, $__WINAPCONSTANT_LOGPIXELSY); Get Pixels Per Inch Y
$TwipsPerPixelY = 1440 / $PixelsPerInchY
$PixelsPerInchX = _WinAPI_GetDeviceCaps($hPrintDc, $__WINAPCONSTANT_LOGPIXELSX); Get Pixels Per Inch X
$TwipsPerPixelX = 1440 / $PixelsPerInchX

; get page width and height
$PageWidth = _WinAPI_GetDeviceCaps($hPrintDc, $HORZRES); Get width, in millimeters, of the physical screen
$PageHeight = _WinAPI_GetDeviceCaps($hPrintDc, $VERTRES); Get height, in millimeters, of the physical screen.

; set docinfo
$s_DocName = "Printing from AutoIt with WinAPI"
$DocName = DllStructCreate("char DocName[" & StringLen($s_DocName & chr(0)) & "]")
DllStructSetData($DocName, "DocName", $s_DocName & chr(0)); Size of DOCINFO structure
$DOCINFO = DllStructCreate($tagDOCINFO); Structure for Print Document info
DllStructSetData($DOCINFO, "Size", 20); Size of DOCINFO structure
DllStructSetData($DOCINFO, "DocName", DllStructGetPtr($DocName)); Set name of print job (Optional)

; start new print doc
$result = _WinAPI_StartDoc($hPrintDc, $DOCINFO)
; start new page
$result = _WinAPI_StartPage($hPrintDc)
#region gdi -------------------------------------------------------
    _GDIPlus_Startup ()
    $hGraphic = _GDIPlus_GraphicsCreateFromHDC ($hPrintDc)
    $hBrush = _GDIPlus_BrushCreateSolid (0x7F00007F)
    $hFormat = _GDIPlus_StringFormatCreate ()
    $hFamily = _GDIPlus_FontFamilyCreate ("Arial")
    $hFont = _GDIPlus_FontCreate ($hFamily, 12, 2)
    $tLayout = _GDIPlus_RectFCreate (140, 110, 100, 20)
    _GDIPlus_GraphicsDrawStringEx ($hGraphic, "Hello world", $hFont, $tLayout, $hFormat, $hBrush)


 ; Clean up resources
    _GDIPlus_FontDispose ($hFont)
    _GDIPlus_FontFamilyDispose ($hFamily)
    _GDIPlus_StringFormatDispose ($hFormat)
    _GDIPlus_BrushDispose ($hBrush)
    
     Global $aPoints[9][2]
     $aPoints[0][0] =7
    $aPoints[1][0] = 50
    $aPoints[1][1] = 50
    $aPoints[2][0] = 100
    $aPoints[2][1] = 25
    $aPoints[3][0] = 200
    $aPoints[3][1] = 5
    $aPoints[4][0] = 250
    $aPoints[4][1] = 50
    $aPoints[5][0] = 300
    $aPoints[5][1] = 100
    $aPoints[6][0] = 350
    $aPoints[6][1] = 200
    $aPoints[7][0] = 250
    $aPoints[7][1] = 250

    _GDIPlus_GraphicsDrawClosedCurve ($hGraphic, $aPoints)
    
;####################
;$hBitmap1 = _ScreenCapture_Capture ("")
; $hImage1 = _GDIPlus_BitmapCreateFromHBITMAP ($hBitmap1)

 ; Capture screen region
    $hBitmap2 = _ScreenCapture_Capture ("", 0, 0, 400, 300)
    $hImage2 = _GDIPlus_BitmapCreateFromHBITMAP ($hBitmap2)

 ; Draw one image in another
 ;$hGraphic = _GDIPlus_ImageGetGraphicsContext ($hImage1)
    _GDIPLus_GraphicsDrawImageRect($hGraphic, $hImage2, 100, 400, 400, 300)

 ; Draw a frame around the inserted image
    _GDIPlus_GraphicsDrawRect ($hGraphic, 100, 400, 400, 300)
    
    
    
;#######################
    
    
    
    _GDIPlus_GraphicsDispose ($hGraphic)
    _GDIPlus_Shutdown ()

#endregion gdi ---------------------------------------------
; End the page
$result = _WinAPI_EndPage($hPrintDc)
; End the print job
$result = _WinAPI_EndDoc($hPrintDc)
; Delete the printer device context
_WinAPI_DeleteDC($hPrintDc)

Func _GetDefaultPrinter()
    Local $szDefPrinterName
    Local $Size
    $namesize = DllStructCreate("dword")
    DllCall("winspool.drv", "int", "GetDefaultPrinter", "str", '', "ptr", DllStructGetPtr($namesize))
    $pname = DllStructCreate("char[" & DllStructGetData($namesize, 1) & "]")
    DllCall("winspool.drv", "int", "GetDefaultPrinter", "ptr", DllStructGetPtr($pname), "ptr", DllStructGetPtr($namesize))
    Return DllStructGetData($pname, 1);msgbox(0,dllstructgetdata($namesize,1),DllStructGetData($pname,1))
EndFunc;==>GetDefaultPrinter1

EDIT: I hadn't noticed tobias7' post, he was a bit ahead of me.

Edited by martin

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.

Share this post


Link to post
Share on other sites

#11 ·  Posted (edited)

A simple version of a function to list the locally installed or connected printers which might be useful.

Const $PRINTER_INFO_4 = "dword;dword;dword"
Const $PRINTER_ENUM_LOCAL = 0x2
Const $PRINTER_ENUM_CONNECTIONS = 0x4
Const $PRINTER_ENUM_NAME = 0x8

MsgBox(262144, "printers on this PC are", StringReplace(_ENumPrinters(6), '|', @CR))

;###########################################################################################
;_EnumPrinters returns a concatenated list of the locally installed and connected printers separated by '|'
;Parameters - $flags = 2 for local printers
;                   = 4 for connected printers
;                   = 6 for both
;Returns on success
;             a concatenated list of the locally installed printers separated by '|'
;      on failure
;            an empty string with @error set to 1
; martin
;############################################################################################shdspl
Func _ENumPrinters($flags = $PRINTER_ENUM_LOCAL)
    Local $plist

;stop illegal flags
    $flags = BitAND($flags, BitOR($PRINTER_ENUM_CONNECTIONS, $PRINTER_ENUM_LOCAL))
    If $flags = 0 Then Return SetError(1, 1, '')
    
    Local $Name = ''
    Local $level = 4;uses gets printer_Info_4 which uses registry. Could be done with Printer_Info_2 but can cause long delay
                   ; if printer no longer installed or remote PC not available.   
     
    Local $cbBuf = 0;no space allowed but we will be told how much is needed
    Local $struct_enum = DllStructCreate("char[" & $cbBuf & "]")
    Local $pPrinterEnum = DllStructGetPtr($struct_enum)

    Local $pcbNeeded, $pcReturned, $n, $printerdesc, $thisPrinter
    $ret = DllCall("winspool.drv", "int", "EnumPrinters", "dword", $flags, "str", $Name, "dword", $level, "ptr", $pPrinterEnum, _
            "dword", $cbBuf, "dword*", $pcbNeeded, "dword*", $pcReturned)
    If @error Then Return SetError(1, 1, "")
    
    If $ret[6] > $ret[5] Then; if we need more space than we allowed
        $struct_enum = DllStructCreate("char[" & $ret[6] & "]")
        $pPrinterEnum = DllStructGetPtr($struct_enum)
        $ret = DllCall("winspool.drv", "int", "EnumPrinters", "dword", $flags, "str", $Name, "dword", $level, "ptr", $pPrinterEnum, _
                "dword", $ret[6], "dword*", $pcbNeeded, "dword*", $pcReturned)
        If @error Then Return SetError(2, 2, "")
    EndIf
    
    For $n = 0 To $ret[7] - 1;for each $PRINTER_INFO_4 structure in the array of $PRINTER_INFO_4's returned
        $ans = DllStructCreate($PRINTER_INFO_4, $pPrinterEnum + $n *12)
        
        $n1 = DllStructCreate("char[256]", DllStructGetData($ans, 1));2 for info_1
        
        $printerdesc = DllStructGetData($n1, 1)
        
        If StringInStr($printerdesc, ',') Then
            $thisPrinter = StringLeft($printerdesc, StringInStr($printerdesc, ',') - 1)
        Else
            $thisPrinter = $printerdesc
        EndIf
        
        If $thisPrinter <> '' Then $plist &= $thisPrinter & '|'
        
    Next
    
    If $plist = "" Then Return $plist
    
    Return StringLeft($plist, StringLen($plist) - 1)
EndFunc  ;==>_ENumPrinters

EDIT: added parameter $flags, corrected returns.

EDIT2: Decided to change to use PRINTER_INFO_4 because it is not reliant on connections existing to other PCs which could be down.

Edited by martin

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

Was reading about printers something and found this topic speaking of it. Nice martins' functions and others of course (I was focused on winspool.drv)

I added some error checking to _GetDefaultPrinter() and unicode support. And three more functions:

#NoTrayIcon

$sPrinter = _GetDefaultPrinter()
ConsoleWrite("Default printer: " & $sPrinter & @CRLF)

$hPrinter = _OpenPrinter($sPrinter)
ConsoleWrite("Printer handle: " & $hPrinter & @CRLF)



; GUI...

$hGui = GUICreate("winspool.drv", 400, 200)
$hButton = GUICtrlCreateButton("Printer Properties Window", 50, 50, 140, 30)
GUISetState(@SW_SHOW)



While 1

    Switch GUIGetMsg()
        Case - 3
            ExitLoop
        Case $hButton
            _PrinterPropertiesWindow($hPrinter, $hGui)
    EndSwitch

WEnd

ConsoleWrite("Close printer: " & _ClosePrinter($hPrinter) & @CRLF)



;Functions...

Func _PrinterPropertiesWindow($hPrinter, $hOwner = 0)

    Local $a_iCall = DllCall("winspool.drv", "int", "PrinterProperties", "hwnd", $hOwner, "hwnd", $hPrinter)

    If @error Or Not $a_iCall[0] Then
        Return SetError(1, 0, "")
    EndIf

    Return SetError(0, 0, 1)

EndFunc   ;==>_PrinterPropertiesWindow



Func _OpenPrinter($sPrinterName)

    Local $a_iCall = DllCall("winspool.drv", "int", "OpenPrinterW", "wstr", $sPrinterName, "hwnd*", 0, "ptr", 0)

    If @error Or Not $a_iCall[0] Then
        Return SetError(1, 0, "")
    EndIf

    Return SetError(0, 0, $a_iCall[2])

EndFunc   ;==>_OpenPrinter



Func _ClosePrinter($hPrinter)

    Local $a_iCall = DllCall("winspool.drv", "int", "ClosePrinter", "hwnd", $hPrinter)

    If @error Or Not $a_iCall[0] Then
        Return SetError(1, 0, "")
    EndIf

    Return SetError(0, 0, 1)

EndFunc   ;==>_ClosePrinter



Func _GetDefaultPrinter()

    Local $a_iCall = DllCall("winspool.drv", "int", "GetDefaultPrinterW", "wstr", "", "dword*", 0)

    If @error Or $a_iCall[0] Then
        Return SetError(1, 0, "")
    EndIf

    Local $iBufferSize = $a_iCall[2]

    $a_iCall = DllCall("winspool.drv", "int", "GetDefaultPrinterW", "wstr", "", "dword*", $iBufferSize)

    If @error Or Not $a_iCall[0] Then
        Return SetError(1, 0, "")
    EndIf

    Return SetError(0, 0, $a_iCall[1])

EndFunc   ;==>_GetDefaultPrinter

I was pleasantly suprised when I found this, really.

Edited by trancexx

♡♡♡

.

eMyvnE

Share this post


Link to post
Share on other sites

#13 ·  Posted (edited)

Really nice... was asked about setting the default Printer before and couldn't answer, but this inspired be...

Enumerate Printers & Set Default Printer (as usual without any satisfying error handling :) )

_EnumPrinters() returns an array with names of printers installed

_SetDefaultPrinter($sPrinter) uses a new of an installed printer to be set as new default printer

Edit:

Guess _WinAPI_SetDefaultPrinter() does the same as _SetDefaultPrinter($sPrinter).

#include <GUIConstantsEx.au3>

Opt("GUIOnEventMode", 1)

Local $sPrinters

$hGUI = GUICreate("Set Default Printer", 300, 100)
GUISetOnEvent($GUI_EVENT_CLOSE, "_Exit")

$cComboboxPrinters = GUICtrlCreateCombo('', 50, 20, 200)
$aPrinters = _EnumPrinters()
For $i = 0 To UBound($aPrinters) - 1
    $sPrinters &= $aPrinters[$i] & "|"
Next
$sPrinters = StringLeft($sPrinters, StringLen($sPrinters) - 1)
GUICtrlSetData(-1, $sPrinters, _GetDefaultPrinter())

GUICtrlCreateButton("Set New Default Printer", 50, 60, 200)
GUICtrlSetOnEvent(-1, "_ChangeDefaultPrinter")

GUISetState()
While 1
    Sleep(10)
WEnd




Func _EnumPrinters()
    $i = 1
    While 1
        $var = RegEnumVal("HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Devices\", $i)
        If @error <> 0 Then ExitLoop
        If StringInStr(RegRead("HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Devices\", $var), "winspool") Then
            If Not IsDeclared('aPrinters') Then
                Local $aPrinters[1]
                $aPrinters[UBound($aPrinters) - 1] = $var
            Else
                ReDim $aPrinters[UBound($aPrinters) + 1]
                $aPrinters[UBound($aPrinters) - 1] = $var
            EndIf
        EndIf
        $i += 1
    WEnd
    Return $aPrinters
EndFunc   ;==>_EnumPrinters

Func _SetDefaultPrinter($sPrinter)
    If StringInStr(RegRead("HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Devices\", $sPrinter), "winspool") Then
        DllCall("winspool.drv", "int", "SetDefaultPrinterW", "wstr", $sPrinter)
    EndIf
EndFunc   ;==>_SetDefaultPrinter

Func _GetDefaultPrinter()

    Local $a_iCall = DllCall("winspool.drv", "int", "GetDefaultPrinterW", "wstr", "", "dword*", 0)

    If @error Or $a_iCall[0] Then
        Return SetError(1, 0, "")
    EndIf

    Local $iBufferSize = $a_iCall[2]

    $a_iCall = DllCall("winspool.drv", "int", "GetDefaultPrinterW", "wstr", "", "dword*", $iBufferSize)

    If @error Or Not $a_iCall[0] Then
        Return SetError(1, 0, "")
    EndIf

    Return SetError(0, 0, $a_iCall[1])

EndFunc   ;==>_GetDefaultPrinter

Func _ChangeDefaultPrinter()
    _SetDefaultPrinter(GUICtrlRead($cComboboxPrinters))
EndFunc   ;==>_ChangeDefaultPrinter

Func _Exit()
    Exit
EndFunc   ;==>_Exit
Edited by KaFu

Share this post


Link to post
Share on other sites

i have this problem when i try to run the script

C:\Program Files\AutoIt3\Include\PrintWinAPI.au3(124,80) : ERROR: _WinAPI_CreatePen() already defined.
Func _WinAPI_CreatePen($iPenStyle = $PS_SOLID, $iWidth = 0, $iColor = 0x000000)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
C:\Program Files\AutoIt3\Include\PrintWinAPI.au3(155,42) : ERROR: _WinAPI_LineTo() already defined.
Func _WinAPI_LineTo($hDC, $iXEnd, $iYEnd)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
C:\Program Files\AutoIt3\Include\PrintWinAPI.au3 - 2 error(s), 0 warning(s)

Share this post


Link to post
Share on other sites

i have this problem when i try to run the script

C:\Program Files\AutoIt3\Include\PrintWinAPI.au3(124,80) : ERROR: _WinAPI_CreatePen() already defined.
Func _WinAPI_CreatePen($iPenStyle = $PS_SOLID, $iWidth = 0, $iColor = 0x000000)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
C:\Program Files\AutoIt3\Include\PrintWinAPI.au3(155,42) : ERROR: _WinAPI_LineTo() already defined.
Func _WinAPI_LineTo($hDC, $iXEnd, $iYEnd)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
C:\Program Files\AutoIt3\Include\PrintWinAPI.au3 - 2 error(s), 0 warning(s)

Just comment or remove these functions.

They didn't exist in previous Autoit versions so he declared them himdelf

but now it's part of Autoit (WinAPI UDF).

Share this post


Link to post
Share on other sites

hi GRS, i don't know why, my browser cannot view your script correctly can you repost the script, as what i can see is overlapping texts.

TQ in advance.

 

Share this post


Link to post
Share on other sites

#17 ·  Posted (edited)

diehardfans,

Did you notice that the first post in this thread dates from over 7 years ago and that the OP has not been online for very nearly the same time?

I have fixed the formatting for you but you should realise that with code this old:

- 1. Some functions might well be included in core or UDF code by now

- 2. The changes in language syntax mean that it is likely that the code will run under the current release interpreter without significant modification.

So good luck!

M23

 

Edited by Melba23

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now