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

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

  ///

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

  public static extern int RegSetValueEx(

   UIntPtr hkey, String lpValueName, uint Reserved, KeyType dwType,

   byte[] lpData, uint cbData);


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

  public static extern int RegDeleteValue(UIntPtr hkey, string valueName);


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

  public static extern int RegCloseKey(UIntPtr hkey);

 }

}

Наличие внешней клавиатуры

С помощью класса Registry разработчик может получать или устанавливать значения параметров в реестре. Предположим, что нужно узнать, подключена ли к устройству внешняя клавиатура. За данную функцию отвечает параметр HasKeyboard в разделе HKEY_CURRENT_USER\Software\Microsoft\Shell. Если данный параметр имеет единичное значение, то система работает с подключенной внешней клавиатурой. Если значение равно нулю, то клавиатуры нет. В листинге 13.18 приведен код, показывающий, как можно извлечь значение интересующего параметра.

Листинг 13.18

private void butCheckKeyboard_Click(object sender, EventArgs e) {

 uint check = 0;

 Registry.GetDWORDValue(Registry.HKCU, "SOFTWARE\\Microsoft\\Shell",

  "HasKeyboard", ref check);

 lblInfo.Text = Convert.ToBoolean(check).ToString();

}

В этом примере используется функция-оболочка GetDWORDValue из класса Registry. Если же вы предпочитаете обходиться без функций-оболочек, а обращаться напрямую к функциям API, то пример можно переписать так, как показано в листинге 13.19.

Листинг 13.19

private static bool IsKeyboard() {

 uint dwordResult;

 UIntPtr hkey = UIntPtr.Zero;

 try {

  int result =

   Registry.RegOpenKeyEx(Registry.HKCU, "SOFTWARE\\Microsoft\\Shell", 0,

   Registry.KeyAccess.None, ref hkey);

  if (Registry.ERROR_SUCCESS != result) return false;

  byte[] bytes = null;

  uint length = 0;

  Registry.KeyType keyType = Registry.KeyType.None;

  result =

   Registry.RegQueryValueEx(hkey, "HasKeyboard", IntPtr.Zero, ref keyType,

   null, ref length);

  if (Registry.ERROR_SUCCESS != result) return false;

  bytes = new byte[Marshal.SizeOf(typeof(uint))];

  length = (uint)bytes.Length;

  keyType = Registry.KeyType.None;

  result =

   Registry.RegQueryValueEx(hkey, "HasKeyboard", IntPtr.Zero, ref keyType,

   bytes, ref length);

  if (Registry.ERROR_SUCCESS != result) return false;

  dwordResult = BitConverter.ToUInt32(bytes, 0);

  return (dwordResult == 1);

 } finally {

  if (UIntPtr.Zero != hkey) {

   Registry.RegCloseKey(hkey);

  }

 }

}

Теперь эту функцию можно вызвать в любом месте программы, как показано в листинге 13.20.

Листинг 13.20

// Определяем наличие внешней клавиатуры

lblInfo.Text = IsKeyboard().ToString();

ВНИМАНИЕ

Следует, отметить, что при проверке примера на эмуляторе функция обнаруживает присутствие клавиатуры. Что, в общем-то, справедливо, так как с помощью обычной клавиатуры пользователь может вводить данные в программах, запущенных на эмуляторе.

Информация о пользователе

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

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

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

Стивен Прата

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