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

 string szTarget);


private void butCreateShortcut_Click(object sender, EventArgs e) {

 // Создадим ярлык к калькулятору

 bool success = SHCreateShortcut("\\My Documents\\Shortcut.lnk",

  "\\Windows\\calс.exe\"");

}

В этом примере создается ярлык Shortcut.lnk для стандартного калькулятора, чей исполняемый файл носит имя windows\calc.exe.

Количество строк в текстовом поле

Если у текстового поля свойство Multiline имеет значение True, то свойство Lines возвращает массив строк в текстовом поле. Но у данного свойства есть два недостатка. Во-первых, свойство Lines не поддерживается библиотекой .NET Compact Framework, а во-вторых, это свойство не учитывает перенос слов. Для подсчета количества строк в многострочном текстовом поле можно использовать сообщение EM_GETLINECOUNT. Соответствующий код приведен в листинге 13.16.

Листинг 13.16

[DllImport("coredll.dll")]

static extern int SendMessage(IntPtr hwnd, int msg, int wParam, int lParam);


const int EM_GETLINECOUNT = 0x00BA;

private void butGetNumber_Click(object sender, EventArgs e) {

 // Узнаем число строк в текстовом поле

 int numberOfLines = SendMessage(textBox1.Handle, EM_GETLINECOUNT, 0, 0);

 sbInfo.Text = "Число строк: " + numberOfLines.ToString();

}

Реестр

Реестр является важной частью любой операционной системы семейства Windows. Не является исключением и система Windows Mobile, в которой тоже имеется собственный реестр. Однако разработчики компании Microsoft не стали включать редактор реестра в состав Windows Mobile. Поэтому для доступа к разделам реестра приходится устанавливать программы от сторонних производителей.

Однако любой программист может написать свой редактор реестра, используя возможности .NET Compact Framework. При этом следует учитывать, что в библиотеке .NET Compact Framework 2.0 появились классы для работы с разделами реестра. Если же вы продолжаете писать программы с использованием .NET Compact Framework 1.0, то придется вызывать функции Windows API.

В листинге 13.17 приведен код, который будет работать в любой версии .NET Compact Framework.

Листинг 13.17

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.InteropServices;


namespace Registry_CS {

 class Registry {

  ///

  /// Создает ключ

  ///

  /// Имя создаваемого ключа

  /// B успешном случае возвращается

  /// ERROR_SUCCESS

  public static int CreateKey(UIntPtr root, string keyName) {

   UIntPtr hkey = UintPtr.Zero;

   uint disposition = 0;

   try {

    return

     RegCreateKeyEx(root, keyName, 0, null, 0, KeyAccess.None, IntPtr.Zero,

      ref hkey, ref disposition);

   } finally {

    if (UIntPtr.Zero != hkey) {

     RegCloseKey(hkey);

    }

   }

  }


  ///

  /// Удаляет ключ

  ///

  /// Имя ключа

  /// B успешном случае возвращается

  /// ERROR_SUCCESS

  public static int DeleteKey(UIntPtr root, string keyName) {

   return RegDeleteKey(root, keyName);

  }


  ///

  /// Создает строковой параметр в заданном ключе

  ///

  /// Имя ключа

  /// Имя параметра

  /// Значение параметра

  /// В успешном случае возвращается

  /// ERROR_SUCCESS

  public static int CreateValueString(string keyName, string valueName,

   string stringData) {

   UIntPtr hkey = UintPtr.Zero;

   try {

    int result = RegOpenKeyEx(root, keyName, 0, KeyAccess.None, ref hkey);

    if (ERROR_SUCCESS != result) return result;

    byte[] bytes = Encoding.Unicode.GetBytes(stringData);

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

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

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

Стивен Прата

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