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

  public Form1() {

   InitializeComponent();

   InitializeComponent();

#if DEBUG

   MinimizeBox = false;

#else

   MinimizeBox = true;

#endif

  }


  private void butResource_Click(object sender, EventArgs e) {

   Sound sound =

    new Sound(Assembly.GetExecutingAssembly().GetManifestResourceStream(

     "PlaySound_CS.chimes.wav"));

   sound.Play();

  }


  private void butFile_Click(object sender, EventArgs e) {

   Sound sound = new Sound("Windows\\alarm3.wav");

   sound.Play();

  }

 }

}

Системные звуки

Также разработчик может использовать функцию MessageBeep, позволяющую проигрывать системные звуки. Код, использующий эту функцию, приведен в листинге 13.13.

Листинг 13.13

[DllImport("coredll.dll")]

extern static void MessageBeep(uint BeepType);


private void butBeep_Click(object sender, EventArgs e) {

 MessageBeep(0);

}

Системное время

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

Листинг 13.14

using System.Runtime.InteropServices;


[DllImport("coredll.dll")]

private extern static void GetSystemTime(ref SYSTEMTIME lpSystemTime);


[DllImport("coredll.dll")]

private extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);


private struct SYSTEMTIME {

 public ushort wYear;

 public ushort wMonth;

 public ushort wDayOfWeek;

 public ushort wDay;

 public ushort wHour;

 public ushort wMinute;

 public ushort wSecond;

 public ushort wMilliseconds;

}


private void GetTime() {

 // Получим системное время

 SYSTEMTIME st = new SYSTEMTIME();

 GetSystemTime(ref st);

 DateTime dt = DateTime.UtcNow.ToLocalTime();

 // Выводим сообщение

 MessageBox.Show("Текущее время: " + st.wHour.ToString() + ":" +

  st.wMinute.ToString());

}


private void SetTime() {

 // Сначала получим системное время

 SYSTEMTIME st = new SYSTEMTIME();

 GetSystemTime(ref st);

 // А теперь прибавим один час

 st.wHour = (ushort)(st.wHour + 1 % 24);

 SetSystemTime(ref st);

 MessageBox.Show("Новое время: " + st.wHour.ToString() + ":" +

  st.wMinute.ToString());

}


private void butGetTime_Click(object sender, EventArgs e) {

 GetTime();

}


private void butSetTime_Click(object sender, EventArgs e) {

 SetTime();

}

Создание ярлыка

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

Листинг 13.15

///

/// Функция для создания ярлыка

///

/// Строка, содержащая

/// путь и имя создаваемого ярлыка.

///

/// Строка, содержащая

/// путь и аргументы для ярлыка.

/// Размер строки ограничен 256 символами.

///

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

/// в случае ошибки возвращается FALSE

///

[DllImport("coredll.dll", EntryPoint = "SHCreateShortcut")]

private static extern bool SHCreateShortcut(string szShortcut,

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

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

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

Стивен Прата

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