Читаем Программирование КПК и смартфонов на .NET Compact Framework полностью

private void butReboot_Click(object sender, EventArgs e) {

 ExitWindowsEx(EWX_REBOOT, 0);

}

Поворот экрана

Начиная с версии операционной системы PocketPC 2003 Second Edition, карманные компьютеры научились изменять ориентацию экрана на системном уровне. Эту возможность часто используют при создании игр, просмотре видеоматериалов или отображении текстов. Если вы планируете писать программу с учетом поворота экрана, то будет нужно проверить, поддерживает ли целевое устройство данную функциональность. Ведь многие пользователи еще владеют КПК на базе PocketPC 2000, PocketPC 2002 и PocketPC 2003.

Для поворота экрана, а также для проверки возможности такого поворота используется функция API ChangeDisplaySettingsEx. Данная функция использует структуру DEVMODE. В первую очередь, в этой структуре нас интересует поле Fields, в котором хранится значение DisplayQueryOrientation. Этот флаг отвечает за поддержку смены ориентации экрана и передает значение в поле lpDevMode.dmDisplayOrientation. Например, значение DMO_0 говорит о том, что поворот экрана не поддерживается.

В листинге 13.5 приведен код, который проверяет, поддерживается ли системой изменение ориентации, и в случае положительного ответа поворачивает экран на 90°.

Листинг 13.5

// Флаг, определяющий поддержку поворота экрана

private static Int32 DisplayQueryOrientation = 0x01000000;


private static Int32 CDS_TEST = 2;


// запоминаем настройки экрана

ScreenOrientation initialOrientation = SystemSettings.ScreenOrientation;

[DllImport("coredll.dll", SetLastError = true)]

private extern static Int32 ChangeDisplaySettingsEx(

 String deviceName, ref DeviceMode deviceMode, IntPtr hwnd,

 Int32 flags, IntPtr param);


struct DeviceMode {

 [MarshalAs(UnmanagedType.ByValTStr, SizeConst - 32)]

 public String DeviceName;

 public Int16 SpecVersion;

 public Int16 DriverVersion;

 public Int16 Size;

 public Int16 DriverExtra;

 public Int32 Fields;

 public Int16 Orientation;

 public Int16 PaperSize;

 public Int16 PaperLength;

 public Int16 PaperWidth;

 public Int16 Scale;

 public Int16 Copies;

 public Int16 DefaultSource;

 public Int16 PrintQuality;

 public Int16 Color;

 public Int16 Duplex;

 public Int16 Yresolution;

 public Int16 TTOption;

 public Int16 Collate;

 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]

 public String FormName;

 public Int16 LogPixels;

 public Int32 BitsPerPel;

 public Int32 PelsWidth;

 public Int32 PelsHeight;

 public Int32 DisplayFlags;

 public Int32 DisplayFrequency;

 public Int32 DisplayOrientation;

}


private void butCheckRotate_Click(object sender, EventArgs e) {

 // подготавливаем структуру DeviceMode

 DeviceMode devMode = new DeviceMode();

 devMode.Size = (Int16)Marshal.SizeOf(devMode);

 devMode.Fields = DisplayQueryOrientation;

 // Проверяем, поддерживает ли система поворот экрана

 Int32 result =

  ChangeDisplaySettingsEx(null, ref devMode, IntPtr.Zero, CDS_TEST,

   IntPtr.Zero);

 if (result == 0) {

  // Если вызов функции прошел успешно.

  // то проверяем поддержку поворота экрана

  // Если параметр DisplayOrientation имеет ненулевое

  // значение то поворот экрана возможен

  if (devMode.DisplayOrientation != 0) {

Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных