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

Мы сделали еще один шаг вперед. Теперь наш маленький блокнот умеет работать с текстом. Но приложение нужно еще немного доработать. Например, пользователь может во время работы с блокнотом переключиться на другую программу и скопировать в буфер обмена картинку, а затем вернуться обратно к текстовому редактору. Конечно, картинку нельзя вставить в текстовое поле. Поэтому надо проверить тип содержимого в буфере обмена, и если там содержатся не текстовые данные, то нужно заблокировать пункт меню Вставить. Для этого можно использовать функцию IsClipboardFormatAvailable, а проверку данных в буфере обмена выполнять в событии Popup, как показано в листинге 7.34.

Листинг 7.34

[DllImport("Coredll.dll")]

private static extern bool IsClipboardFormatAvailable(uint uFormat);


// константа для буфера обмена

private const uint CF_UNICODETEXT = 13;


public static bool IsText() {

 try {

  return IsClipboardFormatAvailable(CF_UNICODETEXT);

 } catch (Exception ex) {

  MessageBox.Show("He могу понять, что содержится в буфере обмена!");

  return false;

 }

}


private void mnuEdit_Popup(object sender, EventArgs e) {

 if (IsText())

  mnuPaste.Enabled = true;

 else

  mnuPaste.Enabled = false;

}

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

Листинг 7.35

//Если текст выделен

if (txtEditor.SelectionLength > 0) {

 mnuCut.Enabled = true;

 mnuCopy.Enabled = true;

 mnuDelete.Enabled = true;

} else {

 mnuCut.Enabled = false;

 mnuCopy.Enabled = false;

 mnuDelete.Enabled = false;

}

Следующим шагом в развитии программы будет добавление файловых операций. Работа с текстовым редактором предполагает не только правку текста, но и сохранение текста в файле, а также чтение данных из файла. Для этого в меню создаются соответствующие команды Создать, Открыть, Сохранить и Сохранить как. Код, связанный с этими командами, приведен в листинге 7.36.

Листинг 7.36

private void mnuOpen_Click(object sender, EventArgs e) {

 dlgOpenFile.Filter = "Текстовые документы (*.txt)|*.txt|Все файлы |*.*";

 dlgOpenFile.ShowDialog();

 if (File.Exists(dlgOpenFile.FileName)) {

  fname = dlgOpenFile.FileName;

  StreamReader sr =

   new StreamReader(fname, System.Text.Encoding.GetEncoding("Windows-1251"), false);

  txtEditor.Text = sr.ReadToEnd();

  flag = false;

  sr.Close();

 }

}


private void mnuSaveAs_Click(object sender, EventArgs e) {

 SaveFileDialog dlgSaveFile = new SaveFileDialog();

 dlgSaveFile.Filter = "Текстовые документы (*.txt)|*.txt|Все файлы |*.*";

 dlgSaveFile.ShowDialog(); fname = dlgSaveFile.FileName;

 savedata();

}


private void savedata() {

 if (fname == "") {

  SaveFileDialog dlgSaveFile = new SaveFileDialog();

  dlgSaveFile.Filter = "Текстовые документы (*.txt)|*.txt|Все файлы|*.*";

  DialogResult res = dlgSaveFile.ShowDialog();

  if (res == DialogResult.Cancel) {

   return;

  }

  fname = dlgSaveFile.FileName;

  MessageBox.Show(fname);

 }

 StreamWriter sw =

  new StreamWriter(fname, false, System.Text.Encoding.GetEncoding("Windows-1251"));

 sw.WriteLine(txtEditor.Text);

 sw.Flush();

 sw.Close();

 flag = false;

}


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

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

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

Стивен Прата

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