Question

Printer Orientation

Asked by: questioner

How do I set the page orentaion of the printer with out using the printer dialog? I have an MDI that some reports should be landscape and some should be portrait. I have not quite been able to figure how to do this.
Thanks.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2000-06-16 at 12:04:30ID10471098
Tags

printer

,

orientation

Topic

Web Ontology Language (OWL)

Participating Experts
2
Points
200
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Setting printer orientation to landscape
    I have an dialog-based application that creates a plot in a CFrameWnd object and a landscape orientation. Most printers, however, are setup for portrait output by default. My application can bring up the print dialog box, but unless the user manually changes the orientation...
  2. Setting Printer to Landscape & Portrait
    How can I set the printer to "Landscape" and to "Portrait"? Thank you.
  3. printer orientation in Crystal Report
    I want to be able to choose the printer orientation to print a crystal report, either in Landscape or Portrait. If I set the printer object property Orientation its not working.
  4. Set landscape or portrait
    The TPrintDialog component does not have a way to set landscape or portrait modes. However, there is a "Properties" button which does bring up a dialog (varies with each make of printer) and on this properties dialog is normally a way to choose landscape or portra...
  5. Changing printer to Landscape /Portrait
    I want to change the printer to Landscape or Portrait in VB code (without opening the Printer Dialog). it must be invisible to the user.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: AlexVirochovskyPosted on 2000-06-16 at 13:33:09ID: 2968196

Next if full code (from MSDN) about changing orientation Printer by Name:

int ChangeOrientation(char *pDevice)
{
   HGLOBAL hGlobal = NULL;
   HGLOBAL hGlobal2 = NULL;
   HANDLE hPrinter = NULL;
   HWND hwnd = 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(pDevice, &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,
                 pDevice,
                 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,
              pDevice,
              pi2->pDevMode, NULL,
              DM_OUT_BUFFER);
      if (lFlag != IDOK)
         goto ABORT;
   }

   /* Specify what we are attempting to change... */
   pi2->pDevMode->dmFields = DM_COPIES;
   pi2->pDevMode->dmCopies = 3;

   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,
         pDevice,
           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) pDevice);
     
      m_lngNCopies = 3;

ABORT:
  return S_OK;
}
I use ~ same code in BC 5.01 and it works file.
I hope, it helps. Alex

 

by: questionerPosted on 2000-06-19 at 08:47:49ID: 2992958

Looks fabulous. Glad to know that it works with BC%.01 (which is what I am using) But one more questions. I don't want to sound dumb but whgat is the pDevice parameter that I am passing it?? Thanks.

 

by: questionerPosted on 2000-06-19 at 09:00:35ID: 2993191

I don't think that is correct for BC5.01.
I put the code into my programs just to give it a test compile and there are several things that are only Microsoft.
The structs: PRINTER_INFO_Z, PRINTER_DEFAULTS, PRINTER_ALL_ACCESS.
The Functions: ZeroMemory(), OpenPrinter, GetPrinter, DocumentProperties, and SetPrinter.

Any other ideas??

Thanks.

 

by: AlexVirochovskyPosted on 2000-06-19 at 22:02:20ID: 3003894

Next is my own working code(from my apps, solded to 15 users), for BC 5.01
This code , i hope, replyes to all
you questions:

/*=======================================================*/
/* Name        : GetPrinterDC                           */
/* Description : Get DC of Default Printer(from WIN.INI) */
/* Arguments   : None                               */
/* Return      : Context or NULL(error)                   */
/*=======================================================*/
HDC GetPrinterDC (HWND hwnd)
{
  HDC hDC = NULL;
  char szPrinter[80], *szDevice, *szDriver, *szOutput;
  memset(szPrinter, 0, sizeof(szPrinter));
  GetProfileString("windows", "device", ",,,", szPrinter,80);
  if (*szPrinter)            //get defoult printer
    {
      if (NULL != (szDevice = strtok(szPrinter,",")) &&
        NULL != (szDriver = strtok(NULL,",")) &&
        NULL != (szOutput = strtok(NULL,",")))
      {
        LPDEVMODE lpDevMode = GetLandscapeDevMode(hwnd,szDevice);
                          //create DC
        hDC = CreateDC(szDriver,szDevice,szOutput,lpDevMode);
        if (lpDevMode)
          free(lpDevMode);
      }
    }
  return hDC;            // if EnumPrinters failed, so return null hdc
}
/*========================================================*/
/* Name        : GetLandscapeDevMode                    */
/* Description : Set Landscape mode(frm MSDN              */
/* Arguments   : Result,1-stSubTitlw,1-st sub text,        */
/*             : 2-stSubTitlw,2-nd sub text,size of Text  */
/*             : current line, Number items in Print,     */
/*             :      delimeter                    */
/* Return val  : None                                */
/*========================================================*/
LPDEVMODE GetLandscapeDevMode(HWND hWnd, char *pDevice)
 {
   HANDLE      hPrinter;
   LPDEVMODE   pDevMode;
   DWORD       dwNeeded, dwRet;

   /* Start by opening the printer */
   if (!OpenPrinter(pDevice, &hPrinter, NULL))
       return NULL;

   /*
    * Step 1:
    * Allocate a buffer of the correct size.
    */
   dwNeeded = DocumentProperties(hWnd,
       hPrinter,       /* handle to our printer */
       pDevice,        /* Name of the printer */
       NULL,           /* Asking for size so */
       NULL,           /* these are not used. */
       0);             /* Zero returns buffer size. */
   pDevMode = (LPDEVMODE)malloc(dwNeeded);

   /*
    * Step 2:
    * Get the default DevMode for the printer and
    * modify it for our needs.
    */
   dwRet = DocumentProperties(hWnd,
       hPrinter,
       pDevice,
       pDevMode,       /* The address of the buffer to fill. */
       NULL,           /* Not using the input buffer. */
       DM_OUT_BUFFER); /* Have the output buffer filled. */
   if (dwRet != IDOK)
   {
       /* if failure, cleanup and return failure */
       free(pDevMode);
       ClosePrinter(hPrinter);
       return NULL;
   }

   /*
        * Make changes to the DevMode which are supported.
    */
   if (pDevMode->dmFields & DM_ORIENTATION)
       /* if the printer supports paper orientation, set it*/
       pDevMode->dmOrientation = DMORIENT_LANDSCAPE;

   /*
    * Step 3:
    * Merge the new settings with the old.
    * This gives the driver a chance to update any private
    * portions of the DevMode structure.
    */
    dwRet = DocumentProperties(hWnd,
       hPrinter,
       pDevice,
       pDevMode,       /* Reuse our buffer for output. */
       pDevMode,       /* Pass the driver our changes. */
       DM_IN_BUFFER |  /* Commands to Merge our changes and */
       DM_OUT_BUFFER); /* write the result. */

   /* Done with the printer */
   ClosePrinter(hPrinter);

   if (dwRet != IDOK)
   {
       /* if failure, cleanup and return failure */
       free(pDevMode);
       return NULL;
   }

   /* return the modified DevMode structure */
   return pDevMode;
}

 

by: questionerPosted on 2000-06-20 at 09:34:48ID: 3011890

Am I doing something wrong? The onlyu place I find the functions OpenPrinter, DocumentProperties and ClosePrinter is in MSVC. Did you write your own functions for these??
Thanks.

 

by: AlexVirochovskyPosted on 2000-06-20 at 10:01:03ID: 3012232

>>Did you write your own functions for these??
No it is standart API .
For example OpenPrinter(from BC help):
-------------
OpenPrinter      

The OpenPrinter function retrieves a handle identifying the specified printer or print server.

BOOL OpenPrinter(

    LPTSTR pPrinterName,      // pointer to printer or server name
    LPHANDLE phPrinter,      // pointer to printer or server handle
    LPPRINTER_DEFAULTS pDefault       // pointer to printer defaults structure  
   );      
 

Parameters

pPrinterName

Points to a null-terminated string that specifies the name of the printer or print server.

phPrinter

Points to a variable that receives the handle identifying the opened printer or print server object.

pDefault

Points to a PRINTER_DEFAULTS structure. This value can be NULL.

 

Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The pDefault parameter allows an application to specify the data type and device mode values that are used for printing documents submitted by the StartDocPrinter function. However, these values can be overridden by using the SetJob function once a document has been started.
The DesiredAccess member of the PRINTER_DEFAULTS data structure pointed to by pDefault specifies the accesses that an application wishes to perform using the handle returned by OpenPrinter
.. If an application wishes to open a printer to perform administrative tasks, such as the SetPrinter function, it should open the printer with PRINTER_ALL_ACCESS access. If an application wishes only to perform basic printing operations, an access value that includes PRINTER_ACCESS_USE is sufficient.

Windows 95: OpenPrinter ignores the DesiredAccess member of PRINTER_DEFAULTS.
An application can determine what permissions a client has on a print server, or obtain a handle to a print server to call WaitForPrinterChange. To do so, it should call OpenPrinter with pPrinterName set to the name of the server and should specify a server access mask value such as SERVER_ALL_ACCESS. The pDatatype and pDevMode members of the PRINTER_DEFAULTS data structure should be set to NULL. The handle returned by such a call may be passed to the ClosePrinter or WaitForPrinterChange function.

If a user does not hold permission to open a specified printer or print server with the desired access, the OpenPrinter call will fail, and GetLastError will return the value ERROR_ACCESS_DENIED.

See Also

ClosePrinter, SetPrinter, StartDocPrinter, WaitForPrinterChange, PRINTER_DEFAULTS

--------
DocumentProperties      

The DocumentProperties function retrieves or modifies printer initialization information or displays a printer-configuration dialog box for the specified printer.

LONG DocumentProperties(

    HWND hWnd,      // handle to window that displays dialog box
    HANDLE hPrinter,      // handle to printer object
    LPTSTR pDeviceName,      // pointer to device name
    PDEVMODE pDevModeOutput,      // pointer to modified device mode structure
    PDEVMODE pDevModeInput,      // pointer to original device mode structure
    DWORD fMode       // mode flag
   );      
 

Parameters

hWnd

Identifies the parent window of the printer-configuration dialog box.

hPrinter

Identifies a printer object.

pDeviceName

Points to a null-terminated string that specifies the name of the device for which the printer-configuration dialog box should be displayed.

pDevModeOutput

Points to a DEVMODE structure that receives the printer configuration data specified by the user.

pDevModeInput

Pointer to a DEVMODE structure that the operating system uses to initialize the dialog box controls.
This parameter is only used if the DM_IN_BUFFER flag is set in the fMode parameter. If DM_IN_BUFFER is not set, the operating system uses the printer's default DEVMODE.

fMode

Specifies a mask of values that determines the operations the function performs. If this parameter is zero, the DocumentProperties function returns the number of bytes required by the printer driver's DEVMODE data structure. Otherwise, use one or more of the following constants to construct a value for this parameter; note, however, that in order to change the print settings, an application must specify at least one input value and one output value:

Value      Meaning
DM_IN_BUFFER      Input value. Before prompting, copying, or updating, the function merges the printer driver's current print settings with the settings in the DEVMODE structure specified by the pDevModeInput parameter. The function updates the structure only for those members specified by the DEVMODE structure's dmFields member. This value is also defined as DM_MODIFY. In cases of conflict during the merge, the settings in the DEVMODE structure specified by pDevModeInput override the printer driver's current print settings.
DM_IN_PROMPT      Input value. The function presents the printer driver's Print Setup dialog box and then changes the settings in the printer's DEVMODE data structure to those values specified by the user. This value is also defined as DM_PROMPT.
DM_OUT_BUFFER      Output value. The function writes the printer driver's current print settings, including private data, to the DEVMODE data structure specified by the pDevModeOutput parameter. The caller must allocate a buffer sufficiently large to contain the information. If the bit DM_OUT_BUFFER sets is clear, the pDevModeOutput parameter can be NULL. This value is also defined as DM_COPY.
 

Return Values

If the fMode parameter is zero, the return value is the size of the buffer required to contain the printer driver initialization data. Note that this buffer can be larger than a DEVMODE structure if the printer driver appends private data to the structure.
If the function displays the initialization dialog box, the return value is either IDOK or IDCANCEL, depending on which button the user selects.
If the function does not display the dialog box and is successful, the return value is IDOK.

If the function fails, the return value is less than zero.

Remarks

The printer object handle identified by the hPrinter parameter can be obtained by calling the OpenPrinter function.
The string pointed to by the pDeviceName parameter can be obtained by calling the GetPrinter function.
Note that the DEVMODE structure actually used by a printer driver contains the device-independent part (as defined above) followed by a driver-specific part that varies in size and content with each driver and driver version. Because of this driver dependence, it is very important for applications to query the driver for the correct size of the DEVMODE structure before allocating a buffer for it.

To make changes to print settings that are local to an application, an application should follow these steps:

      1.      Get the number of bytes required for the full DEVMODE structure by calling DocumentProperties and specifying zero in the fMode parameter.
      2.      Allocate memory for the full DEVMODE structure.
      3.      Get the current printer settings by calling DocumentProperties. Pass a pointer to the DEVMODE structure allocated in Step 2 as the pDevModeOutput parameter and specify the DM_OUT_BUFFER value.
      4.      Modify the appropriate members of the returned DEVMODE structure and indicate which members were changed by setting the corresponding bits in the dmFields member of the DEVMODE.

      5.      Call DocumentProperties and pass the modified DEVMODE structure back as both the pDevModeInput and pDevModeOutput parameters and specify both the DM_IN_BUFFER and DM_OUT_BUFFER values (which are combined using the OR operator).

The DEVMODE structure returned by the third call to DocumentProperties can be used as an argument in a call to the CreateDC function.
To create a handle to a printer-device context using the current printer settings, you only need to call DocumentProperties twice, as described above. The first call gets the size of the full DEVMODE and the second call initializes the DEVMODE with the current printer settings. Pass the initialized DEVMODE to CreateDC to obtain the handle to the printer device context.

See Also

AdvancedDocumentProperties, CreateDC, DEVMODE, GetPrinter, OpenPrinter



 

by: questionerPosted on 2000-06-20 at 16:40:52ID: 3017170

Adjusted points from 100 to 200

 

by: questionerPosted on 2000-06-20 at 16:40:52ID: 3017171

OK I figured out where you are coming from. The problem I was having was that it was set up as a win3.x (16 bit) application instead of a win32 app. Those functions are now valid functions. But now I have a new problem....I should probably post it as a new question but I will start just by boosting thepoints to compensate. Now that it is a win32 app my comm port communications are no longer compilable. I was using functions of importb, CloseComm, WriteComm, OpenComm and SetEventCommMask. What should I be using instead??
Thanks again.

 

by: AlexVirochovskyPosted on 2000-06-20 at 21:29:32ID: 3019934

1. I am very glad to solve you 1-st
   problem.
2. About SerialCommunication:
   Yes, you are right, you must rewrite
code! SerialPort Examples see:      http://codeguru.developer.com/network/serialport.shtml
http://codeguru.developer.com/network/serial.shtml
http://msdn.microsoft.com/library/sdkdoc/winbase/commun_4m7n.htm
http://home.das-netz.de/pat/serial.htm
                  //articles
'http://www.microsoft.com/win32dev/base/serial.htm' -
'http://msdn.microsoft.com/library/techart/msdn_serial.htm'
Small example:
//example of using SerialPort

#include  <windows.h>
#include  <stdio.h>

int main(int argc,char *argv[])
{
  HANDLE  *cfd;
  int     errno;
  int     i;
  int     nBytesRead;
  int     nBytesToRead;
  char    inBuffer[1024];
  int     nBytesWritten;
  int     nBytesToWrite;
  char    outBuffer[1024];

  COMMTIMEOUTS ct;
  DCB          dcb;

  if ( (cfd=CreateFile("COM1:",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL))==INVALID_HANDLE_VALUE ) {
    errno = GetLastError();
    printf("CreatFile failed. Errno=%d\n",errno);
    return -1;
  }
  printf("CreatFile OK\n");
     
  if ( !SetupComm(cfd,1024,1024)!=0 ) {
    errno = GetLastError();
    printf("SetupComm failed. Errno=%d\n",errno);
    return -1;
  }
  printf("SetupComm OK\n");

  if ( !GetCommState(cfd,&dcb) ) {
    errno = GetLastError();
    printf("GetCommState failed. Errno=%d\n",errno);
    return -1;
  }
  printf("GetCommState OK\n");
  printf("DCBlength=0x%04x\n",dcb.DCBlength);
  printf("BaudRate=%d\n",dcb.BaudRate);
  printf("fBinary=0x%04x\n",dcb.fBinary);
  printf("fParity=0x%04x\n",dcb.fParity);
  printf("fOutxCtsFlow=0x%04x\n",dcb.fOutxCtsFlow);
  printf("fOutxDsrFlow=0x%04x\n",dcb.fOutxDsrFlow);
  printf("fDtrControl=0x%04x\n",dcb.fDtrControl);
  printf("fDsrSensitivity=0x%04x\n",dcb.fDsrSensitivity);
  printf("fTXContinueOnXoff=0x%04x\n",dcb.fTXContinueOnXoff);
  printf("fOutX=0x%04x\n",dcb.fOutX);
  printf("fInX=0x%04x\n",dcb.fInX);
  printf("fErrorChar=0x%04x\n",dcb.fErrorChar);
  printf("fNull=0x%04x\n",dcb.fNull);
  printf("fRtsControl=0x%04x\n",dcb.fRtsControl);
  printf("fAbortOnError=0x%04x\n",dcb.fAbortOnError);
  printf("XonLim=0x%02x\n",dcb.XonLim);
  printf("XoffLim=0x%02x\n",dcb.XoffLim);
  printf("ByteSize=0x%02x\n",dcb.ByteSize);
  printf("Parity=0x%02x\n",dcb.Parity);
  printf("StopBits=0x%02x\n",dcb.StopBits);
  printf("XonChar=0x%02x\n",dcb.XonChar);
  printf("XoffChar=0x%02x\n",dcb.XoffChar);
  printf("ErrorChar=0x%02x\n",dcb.ErrorChar);
  printf("EofChar=0x%02x\n",dcb.EofChar);
  printf("EvtChar=0x%02x\n",dcb.EvtChar);

  dcb.BaudRate = 9600;
  if ( !SetCommState(cfd,&dcb) ) {
    errno = GetLastError();
    printf("SetCommState failed. Errno=%d\n",errno);
    return -1;
  }
  printf("SetCommState OK\n");

  if ( !GetCommTimeouts(cfd,&ct) ) {
    errno = GetLastError();
    printf("GetCommTimeouts failed. Errno=%d\n",errno);
    return -1;
  }
  printf("Got CT\n");
  printf("ReadIntervalTimeout=%d\n",ct.ReadIntervalTimeout);
  printf("ReadTotalTimeoutMultiplier=%d\n",ct.ReadTotalTimeoutMultiplier);
  printf("ReadTotalTimeoutConstant=%d\n",ct.ReadTotalTimeoutConstant);
  printf("WriteTotalTimeoutMultiplier=%d\n",ct.WriteTotalTimeoutMultiplier);
  printf("WriteTotalTimeoutConstant=%d\n",ct.WriteTotalTimeoutConstant);

  ct.ReadIntervalTimeout = 10;
  ct.ReadTotalTimeoutMultiplier = 10;
  ct.ReadTotalTimeoutConstant = 10;
  ct.WriteTotalTimeoutMultiplier = 10;
  ct.WriteTotalTimeoutConstant = 50;
  if ( !SetCommTimeouts(cfd,&ct) ) {
    errno = GetLastError();
    printf("SetCommTimeouts failed. Errno=%d\n",errno);
    return -1;
  }
  printf("Set CT\n");

  // Attempt a synchronous write operation.
  nBytesToWrite = 4;
  strcpy(outBuffer,"AT?\r");
  if ( !WriteFile(cfd,outBuffer,nBytesToWrite,&nBytesWritten,NULL) ) {
    printf("No one's home\n");
    return -1;
  }
  printf("BytesWritten: %d\n",nBytesWritten);

  // Attempt a synchronous read operation.
  nBytesToRead = 20;
  if ( !ReadFile(cfd,inBuffer,nBytesToRead,&nBytesRead,NULL) ) {
    printf("EOF\n");
    return -1;
  }
  printf("BytesRead: %d\n",nBytesRead);
  for ( i=0 ; i<nBytesRead ; i++ )
    printf("%02x [%c]\n",inBuffer[i],inBuffer[i]);

  if ( CloseHandle(cfd) )
    printf("Close OK\n");
  else
    printf("Close failed\n");

  return 0;
}
  //load CPL apps
 
    GetStartupInfo(&startUpInfo);
    startUpInfo.dwFlags     &= STARTF_USESHOWWINDOW;
    startUpInfo.wShowWindow &= SW_HIDE;

    success =
    CreateProcess(
        0,                 // pointer to name of executable module
        "Rundll32.exe Shell32.dll,Control_RunDLL timedate.cpl",
                                // pointer to command line string
        0,                 // pointer to process security attributes
        0,                 // pointer to thread security attributes
        FALSE,                 // handle inheritance flag
        CREATE_NEW_CONSOLE, // creation flags
        0,                 // pointer to new environment block
        0,                 // pointer to current directory name
        &startUpInfo,         // pointer to STARTUPINFO
        &procInfo         // pointer to PROCESS_INFORMATION
    );

}

3. About inport/outport:
  It is not easy, you can or use
  assermbler, or some DLL(I use winio.dll from sysinternals).
 If you want, i can sent you all stuff
with DLL: write you EMail
Alex
>>I should probably post it as a new question
Roule of EE: Only 1 question in you Q!
And about inp/outp:  
Yesteday I got 500*4 PTS (in C++ area)
for reply to inp/outp Q...


 

by: JPMPosted on 2000-06-20 at 22:31:50ID: 3020319

A)Landscape printing :   it 's a FAQ . following are 4 ways of how to do the job.
B) example of converting WIN16 to WIN32 serial acces

HTP
Jean-Paul


A)))))
//////// FIRST one ////////////////////////////////////////////////////////
==> in .H file...
// Class that will change a printer's orientation
// Either set to DMORIENT_LANDSCAPE or DMORIENT_PORTRAIT
//------------------------------------------------------------------------------
class TemporaryPrinterOrientation
{
   public:
      TemporaryPrinterOrientation( TPrinter*, int );
      virtual ~TemporaryPrinterOrientation( );
   private:
   // NOTE: See comment in CPP file...
   //   DEVMODE devMode;
      int oldOrientation;
      TPrinter* printer;
};
==> in .CPP file...

//------------------------------------------------------------------------------
TemporaryPrinterOrientation::TemporaryPrinterOrientation( TPrinter* printer, int tempOrientation )
: printer( printer )
//------------------------------------------------------------------------------
{
   switch( tempOrientation )
   {
      case DMORIENT_LANDSCAPE:
      case DMORIENT_PORTRAIT:
      {
         DEVMODE const* pDevMode = printer->GetSetup( ).GetDevMode( );
//         devMode = *pDevMode;
//         oldOrientation = devMode.dmOrientation;
//         devMode.dmOrientation = tempOrientation;
//         printer->GetSetup( ).SetDevMode( &devMode );
// NOTE: When SetDevMode is executed a global block of memory that
// holds the DEVMODE structure is freed and then re-allocated. This
// appears to cause problems with the PostScript printer driver due
// perhaps to it keeping a copy of the original handle (???).
// In order to work-around this problem with the PostScript driver
// we instead attack the actual global memory itself by casting
// the constant pointer to make it accessible.
         if( pDevMode )
         {
            oldOrientation = ( ( DEVMODE* )pDevMode )->dmOrientation;
            ( ( DEVMODE* )pDevMode )->dmOrientation = tempOrientation;
         }
         break;
      }
      default:
         throw xmsg( "Unknown page orientation" );
   }
}
//------------------------------------------------------------------------------
TemporaryPrinterOrientation::~TemporaryPrinterOrientation( )
{
   DEVMODE const* pDevMode = printer->GetSetup( ).GetDevMode( );
//   devMode = *pDevMode;
//   devMode.dmOrientation = oldOrientation;
//   printer->GetSetup( ).SetDevMode( &devMode );
// NOTE: See above for explanation...
   if( pDevMode )      ( ( DEVMODE* )pDevMode )->dmOrientation = oldOrientation;
}
//////////////////////////////////////////////////////////////
///////////SECOND//////////////////////////////////////////
#include <owl/printer.h>
class TLandPrinter: public TPrinter
 {
    public:
        TLandPrinter () : TPrinter () {}
        bool Print (TWindow *parent, TPrintout &printout, bool prompt);
        {
           DEVMODE *devMode = (DEVMODE *)Data->GetDevMode ();
           devMode->dmOrientation = DMORIENT_LANDSCAPE;
           return TPrinter::Print (parent, printout, prompt);
        }
 };
///////////////////////////////////////////////////////////
///////////THIRD//////////////////////////////////////////
void TSCPrinter::SetOrientation( int x )
{
  DEVMODE* dm = (DEVMODE*) GetSetup().GetDevMode();
  if( dm != 0 )
  {
   dm->dmOrientation = (x ? DMORIENT_PORTRAIT : DMORIENT_LANDSCAPE);
   dm->dmFields |= DM_ORIENTATION;
  }
}
///////////////////////////////////////////////////////////////
////////////FOURTH///////////////////////////////////////////
// hp <=== TPrinter object

DEVMODE *devMode = (DEVMODE *)hp->GetSetup().GetDevMode();
devMode->dmOrientation = Orientation;
DC = new TPrintDC(hp->GetSetup().GetDriverName(),
            hp->GetSetup().GetDeviceName(),
            hp->GetSetup().GetOutputName(), devMode);
////////////////////////////////////////////////////////


B))

Example Converting WIN16 to WIN32 port access
"Technical Articles>>Windows Articles>>Kernel/Base Articles>>Serial Communications in WIN 32"

1.  HANDLE h = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0,
            NULL, OPEN_EXISTING, 0, NULL);
    COMMTIMEOUTS cto = { MAXDWORD, 0, 0, 4, 4 };
    SetCommTimeouts(CommHandle, &cto);
    DCB dcb = { 0 };
    dcb.DCBlength = sizeof(dcb);
    BuildCommDCB("COM1 96,n,8,1", &dcb);
    SetCommState(h, &dcb);  
     
2.  ReadFile(h, buf, ct1, &ct2, NULL); // buf = buffer ct1 size of buf
    WriteFile(h, buf, ct1, &ct2, NULL);  // ct2 =  bytes read/written
    CloseHandle(h);

3.  to increase speed :
    DWORD CALLBACK Notify(void *); // declaration
    DWORD id;
    CloseHandle(CreateThread(NULL, 0, Notify, &h, 0, &id));
   
   DWORD CALLBACK Notify(void *param)
    {
     HANDLE *chp = (HANDLE *) param;
     while (*chp != INVALID_HANDLE_VALUE)
       {
      SetCommMask(*chp, EV_RXCHAR);
      DWORD mask;
           // wait for input char
      if (WaitCommEvent(*chp, &mask, NULL))
                  MainWindow->PostMessage(WM_TIMER);
       }
    return(0);
   }
   


 

by: AlexVirochovskyPosted on 2000-06-24 at 21:25:59ID: 3041416

I hope, my (and JPM) adveces helps you

 

by: questionerPosted on 2000-06-26 at 13:05:03ID: 3077013

Answer accepted

 

by: questionerPosted on 2000-06-26 at 13:05:03ID: 3077014

Yes I thank you both for your help. I was very much appreciated. And I will give the points to both of you. If the amount is not sufficient please let me know. Thanks again for all your help.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...