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

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

[DllImport("coredll.dll")]

private static extern bool GetPasswordActive();


// Функция для проверки пароля [DllImport("coredll.dll")]

private static extern bool CheckPassword(string lpszPassword);


private void butCheckPass_Click(object sender, EventArgs e) {

 txtInfo.Text ="Активность пароля: " + GetPasswordActive().ToString();

}


private void butNewPass_Click(object sender, EventArgs e) {

 MessageBox.Show("Установка нового пароля " +

 SetPassword("Активность пароля: False", txtInfо.Text).ToString());

}


private void butSetState_Click(object sender, EventArgs e) {

 MessageBox.Show("Отключение пароля: " +

 SetPasswordActive(false, txtInfo.Text).ToString());

}


private void butFindPass_Click(object sender, EventArgs e) {

 MessageBox.Show("Угадали пароль? " + CheckPassword(txtInfo.Text).ToString());

}

ВНИМАНИЕ

Будьте осторожны с данными функциями на реальном устройстве. Если вы случайно установите новый пароль, не запомнив его, то вам придется применить жесткую перезагрузку с потерей всех данных!

Перезагрузка КПК

Для карманных компьютеров может применяться как жесткая, так и мягкая перезагрузка. Жесткая перезагрузка возвращает устройство в первоначальное состояние, удаляя все установленные программы. Делать жесткую перезагрузку без особой необходимости не следует. Мягкая перезагрузка является более безопасной операцией, которую часто выполняют при появлении различных сбоев в работе программ.

Если разработчику необходимо программно перезагрузить устройство, то необходимо воспользоваться функцией KernelIoControl. В листинге 13.3 приведен небольшой пример, демонстрирующий мягкую перезагрузку.

Листинг 13.3

public const uint FILE_DEVICE_HAL = 0x00000101;

public const uint METHOD_BUFFERED = 0;

public const uint FILE_ANY_ACCESS = 0;


public uint CTL_CODE(uint DeviceType, uint Function,

 uint Method, uint Access) {

 return

  ((DeviceType << 16) | (Access << 14) | (Function << 2) | Method);

}


[DllImport("Coredll.dll")]

public extern static uint KernelIoControl(

 uint dwIoControlCode, IntPtr lpInBuf, uint nInBufSize, IntPtr lpOutBuf,

 uint nOutBufSize, ref uint lpBytesReturned);


private void butReset_Click(object sender, EventArgs e) {

 uint bytesReturned = 0;

 uint IOCTL_HAL_REBOOT =

  CTL_CODE(FILE_DEVICE_HAL, 15, METHOD_BUFFERED, FILE ANY ACCESS);

 KernelIoControl(IOCTL_HAL_REBOOT, IntPtr.Zero, 0, IntPtr.Zero,

  0, ref bytesReturned);

}

Еще раз о перезагрузке

Для устройств, работающих под управлением Windows Mobile 5.0, существует более удобный способ перезагрузки. Он очень похож на код перезагрузки настольных компьютеров с использованием функции ExitWindowsEx. При этом надо обратить внимание на различия карманных компьютеров и смартфонов. Если КПК можно только перезагрузить, то смартфон можно и перезагрузить, и выключить. Соответствующий код приведен в листинге 13.4.

Листинг 13.4

[DllImport("aygshell.dll")]

public static extern System.Boolean ExitWindowsEx(int uFlags,

 int dwReserved);


const int EWX_REBOOT = 2; // перезагрузка

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

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

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

Стивен Прата

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