HGLOBAL hGlobal = NULL;
   HANDLE hPrinter = NULL;
   DWORD dwNeeded = 0;
   PRINTER_INFO_2 *pi2 = NULL;
   PRINTER_DEFAULTS pd;
   BOOL bFlag;
   LONG lFlag;

   /* Open printer handle (in Windows NT, you need full-access because you
      will eventually use SetPrinter) */

   ZeroMemory(&pd, sizeof(pd));
   pd.DesiredAccess = PRINTER_ALL_ACCESS;
   bFlag = OpenPrinter("My Printer", &hPrinter, &pd);
   if (!bFlag || (hPrinter== NULL))
      goto ABORT;

   /* The first GetPrinter() tells you how big the buffer should be in
      order to hold all of PRINTER_INFO_2. Note that this usually returns
      as FALSE, which only means that the buffer (the third parameter) was
      not filled in. You don't want it filled in here. */

   GetPrinter(hPrinter, 2, 0, 0, &dwNeeded);
   if (dwNeeded == 0)
      goto ABORT;

   /* Allocate enough space for PRINTER_INFO_2. */

   hGlobal = GlobalAlloc(GHND, dwNeeded);
   if (hGlobal == NULL)
      goto ABORT;
   pi2 = (PRINTER_INFO_2 *)GlobalLock(hGlobal);
   if (pi2 == NULL)
      goto ABORT;

   /* The second GetPrinter() fills in all the current settings, so all you
      need to do is modify what you're interested in. */

   bFlag = GetPrinter(hPrinter, 2, (LPBYTE)pi2, dwNeeded, &dwNeeded);
   if (!bFlag)
      goto ABORT;

   /* If GetPrinter didn't fill in the DEVMODE, get it by calling
      DocumentProperties. */

   if (!pi2->pDevMode)
   {
      dwNeeded = DocumentProperties(hwnd, hPrinter,
                 "My Printer",
                 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,
              "My Printer",
              pi2->pDevMode, NULL,
              DM_OUT_BUFFER);
      if (lFlag != IDOK)
         goto ABORT;
   }

   /* Specify what we are attempting to change... */
   pi2->pDevMode->dmFields = DM_ORIENTATION;
   pi2->pDevMode->dmOrientation = DMORIENT_LANDSCAPE;

   /* Make sure the driver-dependent part of devmode is updated as
      necessary. */
   lFlag = DocumentProperties(hwnd, hPrinter,
           "My Printer",
           pi2->pDevMode, pi2->pDevMode,
           DM_IN_BUFFER | DM_OUT_BUFFER);
   if (lFlag != IDOK)
      goto ABORT;

   /* Update printer information. */
   bFlag = SetPrinter(hPrinter, 2, (LPBYTE)pi2, 0);
   if (!bFlag)
      /* The driver doesn't support, or it is unable to make the change. */
      goto ABORT;
   SendMessage(HWND_BROADCAST, WM_DEVMODECHANGE, 0L,
               (LPARAM)(LPCSTR)"My Printer");

   /* Clean up. */
   ABORT:   if (pi2 != NULL)
         GlobalUnlock(hGlobal);
      if (hGlobal != NULL)
         GlobalFree(hGlobal);
      if (hPrinter != NULL)
         ClosePrinter(hPrinter);
