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

/// (\Windows\Start Menu\Programs)

///

const int CSIDL_PROGRAMS = 0x0002;


///

/// Папка Recent (содержит последние из открывавшихся

/// документов)

///

const int CSIDL_RECENT = 0x0008;


///

/// Папка Главное меню

/// (\Windows\Start Menu)

///

const int CSIDL_STARTMENU = 0x000b;


///

/// Папка Автозагрузка для программ,

/// которые автоматически загружаются при запуске Windows

/// \Windows\StartUp

///

const int CSIDL_STARTUP = 0x0007;


///

/// Папка, в которой хранятся шаблоны документов

///

const int CSIDL_TEMPLATES = 0x0015;


///

/// Функция получения имен специальных папок

///

[DllImport("Coredll.dll")]

static extern int SHGetSpecialFolderPath

 (IntPtr hwndOwner, StringBuilder lpszPath, int nFolder, int fCreate);


const int MAX_PATH = 260;


private void Form1_Load(object sender, EventArgs e) {

 // Папка Избранное

 StringBuilder strFavorites = new StringBuilder(MAX_PATH);

 SHGetSpecialFolderPath(this.Handle, strFavorites, CSIDL_FAVORITES, 0);

 MessageBox.Show("Избранное: " + strFavorites.ToString());


 // Папка Программы

 StringBuilder strPrograms = new StringBuilder(MAX_PATH);

 SHGetSpecialFolderPath(this.Handle, strPrograms, CSIDL_PROGRAMS, 0);

 MessageBox.Show("Программы: " + strPrograms.ToString());


 // Мои документы

 StringBuilder strMyDocs = new StringBuilder(MAX_PATH);

 SHGetSpecialFolderPath(this.Handle, strMyDocs, CSIDL_PERSONAL, 0);

 MessageBox.Show("Мои документы: " + strMyDocs.ToString());

}

Использование звуковых файлов

Мир современных компьютеров трудно представить без мультимедийных возможностей; однако проигрывание звуковых файлов не поддерживалось в библиотеке .NET Framework 1.0. Подобный подход Microsoft удивил многих программистов. В этом случае приходилось использовать неуправляемый код с вызовом функции PlaySound.

С выходом .NET Framework 2.0 ситуация изменилась в лучшую сторону. Но легкая поддержка звуковых файлов остается прерогативой настольных систем. В библиотеке .NET Compact Framework по-прежнему отсутствует поддержка проигрывания звуковых файлов. А ведь для разработки игры наличие звуковых эффектов является обязательным условием, иначе игра будет просто неинтересна!

Поэтому нужно устранить недоработку разработчиков из Microsoft. В новом примере будут использоваться два способа воспроизведения звуков. В первом случае программа будет извлекать звуковой фрагмент из ресурсов. Во втором случае программа будет проигрывать звук из обычного WAV-файла.

Итак, нужно создать новый проект с именем PlaySound_CS. К проекту надо добавить новый класс с именем Sound. Объявление функции PlaySound, необходимой для проигрывания звуков, нужно поместить в класс Sound, как показано в листинге 13.10.

Листинг 13.10

private enum Flags {

 SND_SYNC = 0x0000,

 SND_ASYNC = 0x0001,

 SND_NODEFAULT = 0x0002,

 SND_MEMORY = 0x0004,

 SND_LOOP = 0x0008,

 SND_NOSTOP = 0x0010,

 SND_NOWAIT = 0x00002000,

 SND_ALIAS = 0x00010000,

 SND_ALIAS_ID = 0x00110000,

 SND_FILENAME = 0x00020000,

 SND_RESOURCE = 0x00040004

}


[DllImport("CoreDll.DLL", EntryPoint = "PlaySound", SetLastError = true)]

private extern static int PlaySound(string szSound, IntPtr hMod, int flags);


[DllImport("CoreDll.DLL", EntryPoint = "PlaySound", SetLastError = true)]

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

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

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

Стивен Прата

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