Thursday, July 2, 2009

Change the Screen Rotation in your application

Windows Mobile devices allows user to rotate the screen orientation, on some devices, this rotation is automatically done while sliding keyboard is opened to provide the good orientation to user to get a chance to type text using the hardware keyboard. More advanced devices get an accelerometer and can automatically rotate the screen while the user physically rotate the device from portrait to landscape and vice versa.
Windows Embedded CE devices on their side can also have screen rotation enabled, but as they are usually for industrial purposes, this feature is not necessarily enabled.

On both version, when user have to do screen rotation the ChangeDisplaySettingsEx function is used. The sample code below shows up the steps to perform screen rotation.

  1.    
  2. BOOL RotateScreen(int iRotationAngle)  
  3. {  
  4.   int iAngle;  
  5.   
  6.   // Check if rotation angle is a multiple of 90 degres  
  7.   if ((iRotationAngle % 90) != 0)  
  8.   {  
  9.     return FALSE;  
  10.   }  
  11.           
  12.   // Screen rotation is a bit field value  
  13.   // 0 = 0, 1 = 90, 2 = 180, 4 = 270  
  14.   iAngle = iRotationAngle / 90;  
  15.   if( iAngle == 3 )  
  16.     iAngle = 0x4;  
  17.   
  18.   //  
  19.   DEVMODE devMode;  
  20.   memset (&devMode, 0, sizeof (devMode));  
  21.   devMode.dmSize = sizeof (devMode);  
  22.   devMode.dmFields = DM_DISPLAYQUERYORIENTATION;  
  23.   
  24.   // Retrieve the supported screen rotation angles  
  25.   if (DISP_CHANGE_SUCCESSFUL != ChangeDisplaySettingsEx(NULL, &devMode, NULL, CDS_TEST, NULL))  
  26.   {  
  27.     return FALSE;  
  28.   }  
  29.   
  30.   // Check if required screen rotation is supported  
  31.   if (iAngle == 0 || iAngle & devMode.dmDisplayOrientation)  
  32.   {  
  33.     memset(&devMode, 0, sizeof (devMode));  
  34.     devMode.dmSize               = sizeof (devMode);  
  35.     devMode.dmFields             = DM_DISPLAYORIENTATION;  
  36.     devMode.dmDisplayOrientation = iAngle;  
  37.      
  38.     if (DISP_CHANGE_SUCCESSFUL != ChangeDisplaySettingsEx(NULL, &devMode, NULL, CDS_RESET, NULL))  
  39.     {  
  40.        return FALSE;           
  41.     }  
  42.     else return TRUE;  
  43.   }  
  44.   
  45.   return FALSE;  
  46. }  


Thanks to Alban for his help.

- Nicolas

No comments: