// SetPrinterCopy.cpp : コンソール アプリケーションのエントリ ポイントを定義します。
//
#include "stdafx.h"
#include <wtypes.h>
#include <Windows.h>
int main(int argc, char *argv[])
{
//printf("引数の総個数 = %d\n", argc);
//for (i = 0; i < argc; i++) {
// printf("%d番目の引数 = %s\n", i, argv[i]);
//}
if (argc == 1) {
printf("プリンター名が未設定です。\n");
return 0;
}
//プリンター名をLPWSTRへ変換
char* wStrC = argv[1];
//char* wStrC = "DocuCentre-IV C5575";
WCHAR wStrW[100];
size_t wLen = 0;
errno_t err = 0;
err = mbstowcs_s(&wLen, wStrW, 100, wStrC, _TRUNCATE);
LPWSTR ptr = wStrW;
//親ウインドウハンドル取得
HWND hWnd = NULL;
GetParent(hWnd);
//
HGLOBAL hGlobal = NULL;
HGLOBAL hGlobal2 = NULL;
HANDLE hPrinter = NULL;
DWORD dwNeeded = 0;
PRINTER_INFO_2 *pi2 = NULL;
PRINTER_DEFAULTS pd;
BOOL bFlag;
LONG lFlag;
/* プリンタのハンドルをオープン
(Windows NT の場合、SetPrinter にはすべての権限 (ALL_ACCESS) が必要になります)
*/
ZeroMemory(&pd, sizeof(pd));
pd.DesiredAccess = PRINTER_ALL_ACCESS;
bFlag = OpenPrinter(ptr, &hPrinter, &pd);
if (!bFlag || (hPrinter == NULL))
goto ABORT;
/* 最初の GetPrinter() で、PRINTER_INFO_2 全体を格納するのに必要なバッファの
サイズを取得します。この呼び出しでは、FALSE が返ることに注意してください。
*/
GetPrinter(hPrinter, 2, 0, 0, &dwNeeded);
if (dwNeeded == 0)
goto ABORT;
/* PRINTER_INFO_2 に十分なスペースの確保 */
hGlobal = GlobalAlloc(GHND, dwNeeded);
if (hGlobal == NULL)
goto ABORT;
pi2 = (PRINTER_INFO_2 *)GlobalLock(hGlobal);
if (pi2 == NULL)
goto ABORT;
/* 2 回目の GetPrinter() の呼び出しで、現在の設定値を取得します。
アプリケーションでは必要な個所のみ変更することになります。
*/
bFlag = GetPrinter(hPrinter, 2, (LPBYTE)pi2, dwNeeded, &dwNeeded);
if (!bFlag)
goto ABORT;
/* もし GetPrinter で、DEVMODE が取得できなかった場合、DocumentProperties で
取得する
*/
if (!pi2->pDevMode)
{
dwNeeded = DocumentProperties(hWnd, hPrinter,
ptr,
NULL, NULL, 0);
if (dwNeeded <= 0)
goto ABORT;
hGlobal2 = GlobalAlloc(GHND, dwNeeded);
if (!hGlobal2)
goto ABORT;
pi2->pDevMode = (DEVMODE *)GlobalLock(hGlobal2);
if (!pi2->pDevMode)
goto ABORT;
lFlag = DocumentProperties(hWnd, hPrinter,
ptr,
pi2->pDevMode, NULL,
DM_OUT_BUFFER);
if (lFlag != IDOK)
goto ABORT;
}
/* DEVMODE の変更 */
//pi2->pDevMode->dmFields = DM_ORIENTATION;
//pi2->pDevMode->dmOrientation = DMORIENT_LANDSCAPE;
pi2->pDevMode->dmCopies = atoi(argv[2]); //部数の設定
/* DEVMODE のデバイス依存部分のアップデート */
lFlag = DocumentProperties(hWnd, hPrinter,
ptr,
pi2->pDevMode, pi2->pDevMode,
DM_IN_BUFFER | DM_OUT_BUFFER);
if (lFlag != IDOK)
goto ABORT;
/* プリンタ情報のアップデート */
bFlag = SetPrinter(hPrinter, 2, (LPBYTE)pi2, 0);
if (!bFlag)
/* ドライバがサポートしていないか、変更の失敗 */
goto ABORT;
/* 後処理 */
ABORT:
if (hGlobal2 != NULL) {
if (pi2->pDevMode)
GlobalUnlock(hGlobal2);
GlobalFree(hGlobal2);
}
if (pi2 != NULL)
GlobalUnlock(hGlobal);
if (hGlobal != NULL)
GlobalFree(hGlobal);
if (hPrinter != NULL)
ClosePrinter(hPrinter);
return 0;
}