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

using Microsoft.WindowsMobile.Forms;

using Microsoft.WindowsMobile.PocketOutlook;


private void button1_Click(object sender, EventArgs e) {

 // Создаем встречу и устанавливаем детали

 Appointment appt = new Appointment();

 // Тема для встречи

 appt.Subject = "Встреча с тещей";

 // Время встречи - 8 марта 2007 в 22 часа

 appt.Start = new DateTime(2007, 03, 08, 22, 00, 00);

 // Продолжительность встречи - 3 минуты

 appt.Duration = new TimeSpan(00, 03, 00);

 // Использовать виброзвонок для напоминания

 appt.ReminderVibrate = true;

 // Повторять напоминание, пока пользователь не отреагирует

 appt.ReminderRepeat = true;


 // Создаем сессию Outlook

 // добавляем встречу в папку встреч Outlook

 using (OutlookSession session = new OutlookSession()) {

  session.Appointments.Items.Add(appt);

  session.Dispose();

 }

}


Нужно запустить программу и нажать кнопку Добавить встречу. После этого можно закрыть приложение, так как свою работу оно закончило. Теперь следует открыть программу Календарь, которая встроена в систему. В календаре нужно найти дату, которая использовалась в программе. В текущем примере встреча была запланирована на 8 марта 2007 года. Если все сделано правильно, то в указанной дате должна присутствовать запись о новой встрече (рис. 10.5).

Рис. 10.5. Календарь с установленной записью встречи

Работа с адресной книгой

В этом разделе будет рассмотрен пример, в котором будет добавлена новая запись в объект Контакты. Для этого надо, как и прежде, добавить в проект ссылки на соответствующие сборки Miсrosoft.WindowsMobile.Forms и Microsoft.WindowsMobilе.PocketOutlook. А в редакторе кода надо добавить объявления для пространств имен Microsoft.WindowsMobilе.Forms и Microsoft.WindowsMobile.PocketOutlook сразу после существующих объявлений.

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

Листинг 10.2

private OutlookSession session;


public Form1() {

 InitializeComponent();

 // Создаем экземпляр сессии Pocket Outlook

 session = new OutlookSession();

}


private void butAddContact_Click(object sender, EventArgs e) {

 Contact contact = new Contact();

 contact.FirstName = "Билл";

 contact.LastName = "Гейтс";

 contact.Email1Address = "billgates@microsoft.com";

 contact.Birthday = new DateTime(1955,10,28);

 contact.CompanyName = "Microsoft";

 contact.WebPage = new Uri("http://www.microsoft.com");

 session.Contacts.Items.Add(contact);

}

Код очень прост и практически не требует комментариев. В начале работы создается переменная contact, в которой можно задавать самые различные параметры. В этом примере использовались только основные свойства. Были указаны имя, фамилия, электронный адрес, день рождения, имя компании и ее веб-страница. После того как новый контакт будет добавлен в список, нужно закрыть сессию при помощи метода Dispose().

После запуска приложения следует нажать кнопку Добавить в Контакты. В результате этого в списке Контакты появится новая запись (рис. 10.6)

Рис. 10.6. Просмотр списка контактов

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

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

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

Стивен Прата

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