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

Для начала нужно создать новый класс PlatformDetector, в котором следует объявить функцию SystemParametersInfo и методы определения платформы. А в обработчике события Load основной формы надо вызвать метод GetPlatform, чтобы узнать платформу сразу же после загрузки приложения, как это показано в листинге 13.1.

Листинг 13.1

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.InteropServices;


namespace PlatformDetector_CS {

 class PlatformDetector {

  [DllImport("coredll.dll")]

  private static extern bool SystemParametersInfo(int uiAction, int uiParam,

   StringBuilder pvParam, int fWinIni);


  private static int SPI_GETPLATFORMTYPE = 257;


  public static Platform GetPlatform() {

   Platform plat = Platform.Unknown;

   switch (System.Environment.OSVersion.Platform) {

   case PlatformID.Win32NT:

    plat = Platform.Win32NT;

    break;

   case PlatformID.WinCE:

    plat = CheckWinCEPlatform();

    break;

   }

   return plat;

  }


  static Platform CheckWinCEPlatform() {

   Platform plat = Platform.WindowsCE;

   StringBuilder strbuild = new StringBuilder(200);

   SystemParametersInfо(SPI_GETPLATFORMTYPE, 200, strbuild, 0);

   string str = strbuild.ToString();

   switch (str) {

   case "PocketPC":

    plat = Platform.PocketPC;

    break;

   case "SmartPhone":

    // Note that the strbuild parameter from the

    // PInvoke returns "SmartPhone" with an

    // upper case P. The correct casing is

    // "Smartphone" with a lower case p.

    plat = Platform.Smartphone;

    break;

   }

   return plat;

  }

 }


 public enum Platform {

  PocketPC, WindowsCE, Smartphone, Win32NT, Unknown

 }

}


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;


namespace PlatformDetector_CS {

 public partial class Form1 : Form {

  public Form1() {

   InitializeComponent();

  }


  private void Form1_Load(object sender, EventArgs e) {

   try {

    MessageBox.Show("Платформа: " + PlatformDetector.GetPlatform());

   } catch (Exception ex) {

    MessageBox.Show(ex.Message.ToString());

   }

  }

 }

}

Особое внимание следует обратить на комментарий. Параметр strbuild после вызова функции возвращает значение SmartPhone с большой буквой «P», хотя более правильным вариантом считается слово с маленькой буквой «p».

Пароли

Как вы, вероятно, знаете, пользователь может установить пароль на свой карманный компьютер. Для этого ему нужно зайти в раздел Password при помощи последовательности команд Start►Settings►Password и указать четырехсимвольный пароль. С помощью четырех функций API можно получить сведения о пароле и даже попытаться угадать его!

Для тестирования этой возможности на форме надо разместить четыре кнопки и текстовое поле. Соответствующий код приведен в листинге 13.2.

Листинг 13.2

// Функция для установления нового системного пароля

[DllImport("coredll.dll")]

private static extern bool SetPassword(string lpszOldpassword,

 string lspzNewPassword);


// Функция для активации или блокировки текущего пароля

[DllImport("coredll.dll")]

private static extern bool SetPasswordActive(bool bActive,

 string lpszPassword);


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

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

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

Стивен Прата

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