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

 list.Sort(new SimpleComparer());

 foreach(string dir in list) {

  lvi = new ListViewItem(Path.GetFileName(dir));

  lvi.ImageIndex = 0;

  listView.Items.Add(lvi);

 }


 // Добавляем файлы

 string[] files = Directory.GetFiles(path);

 list = new ArrayList(files.Length);

 for(int i = 0; i < files.Length; i++)

  list.Add(files[i]);

 list.Sort(new SimpleComparer());

 foreach(string file in list) {

  lvi = new ListViewItem(Path.GetFileName(file));

  lvi.ImageIndex = 1;

  listView.Items.Add(lvi);

 }

 listView.EndUpdate();

 if (listView.Items.Count > 0) {

  // выделяем первый элемент

  listView.Items[0].Selected = true;

  listView.Items[0].Focused = true;

 }

 Cursor.Current = Cursors.Default;

}

Итак, посмотрим, что делает метод fillList. Перед заполнением элемента списком файлов надо очистить его содержимое от предыдущих записей при помощи метода Clear. После очистки списка надо проверить, является ли папка корневой. Если папка не корневая, то в список добавляется специальная папка «На один уровень выше». Затем в список добавляются все папки в отсортированном порядке.

После этого наступает очередь файлов. Они сортируются и заносятся в список. Наконец, первый элемент списка выделяется другим цветом. Заодно на первом элементе устанавливается фокус ввода. Навигация по папкам и файлам осуществляется с помощью кнопок и дополняется кнопкой Action. Код навигации приведен в листинге 7.11.

Листинг 7.11

///

/// Навигация по папкам и файлам

///

///

///

private void listView_ItemActivate(object sender, System.EventArgs e) {

 Cursor.Current = Cursors.WaitCursor;

 ListViewItem lvi = listView.Items[listView.SelectedIndices[0]];

 bool isFolder = lvi.ImageIndex == 0;

 if (lvi.Text == UPDIR) {

  path = path.Substring(0,

   path.Substring(0,

   path.Length - 1).LastIndexOf(Path.DirectorySeparatorChar) + 1);

  fillList();

 } else if (isFolder) {

  path += lvi.Text + Path.DirectorySeparatorChar;

  fillList();

 } else

  ShellExecute.Start(path + lvi.Text);

 Cursor.Current = Cursors.Default;

}

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

Теперь разберем код для команд меню. Для команды Вырезать код приведен в листинге 7.12.

Листинг 7.12

private void cutMenuItem_Click(object sender, System.EventArgs e) {

 ListViewItem lvi =

  listView.Items[listView.SelectedIndices[0]];

 clipboardFileName = this.path + lvi.Text;

 clipboardAction = ClipboardAction.Cut;

}

Путь к текущему выбранному файлу сопоставляется с производимым действием. Код, выполняющийся после выбора команды Копировать, приведен в листинге 7.13.

Листинг 7.13

private void copyMenuItem_Click(object sender, System.EventArgs e) {

 ListViewItem lvi = listView.Items[listView.SelectedIndices[0]];

 clipboardFileName = path + lvi.Text;

 clipboardAction = ClipboardAction.Copy;

}

Для команды меню Вставить код немного усложняется. Он приведен в листинге 7.14.

Листинг 7.14

private void pasteMenuItem_Click(object sender, System.EventArgs e) {

 // Если файл существует

 string dest = path + Path.GetFileName(clipboardFileName);

 if (File.Exists(dest)) {

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

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

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

Стивен Прата

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