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

Элемент ListBox имеет множество возможностей, которые пока не реализованы в рамках платформы .NET Compact Framework. В частности, данный элемент не позволяет осуществлять поиск элементов по первым символам. Но для решения этой задачи можно использовать сообщение LB_FINDSTRING.

Чтобы создать тестовое приложение, нужно добавить на форму список ListBox и текстовое поле TextBox. Также потребуется ввести код, приведенный в листинге 4.5.

Листинг 4.5

const int LB_FINDSTRING = 0x018F;

const int LB_FINDSTRINGEXACT = 0x01A2;


[DllImport("coredll.dll")]

static extern int SendMessage(IntPtr hwnd, int msg,

 int wParam, string lParam);


private void textBox1_TextChanged(object sender, EventArgs e) {

 //поиск строки по вводимым символам

 listBox1.SelectedIndex =

  SendMessage(listBox1.Handle, LB_FINDSTRING, -1, textBox1.Text);

}


private void Form1_Load(object sender. EventArgs e) {

 listBox1.Items.Add("bank");

 listBox1.Items.Add("banana");

 listBox1.Items.Add("ball");

 listBox1.Items.Add("bounty");

 listBox1.Items.Add("bar");

}

После запуска проекта можно попробовать ввести в текстовом поле любое слово. Если в списке есть слова, начинающиеся с введенных символов, то они начнут выделяться в списке. Например, можно сначала ввести символ b, затем a и, наконец, l. Сначала будет выделено слово bank, а после третьего введенного символа выделение перейдет на слово ball.

Существует также сообщение LB_FINDSTRINGEXACT, которое осуществляет поиск по целому слову без учета регистра. Имеет смысл применять его, когда список содержит сотни записей и отыскивание нужного слова становится утомительным занятием. Чтобы показать применение этого сообщения, нужно добавить в предыдущий пример дополнительную кнопку и ввести код, приведенный в листинге 4.6.

Листинг 4.6

private void button1_Click(object sender, EventArgs e) {

 listBox1.SelectedIndex =

  SendMessage(listBox1.Handle, LB_FINDSTRINGEXACT, -1, "ball");

}

ListView

Возможно, вы замечали, что в некоторых программах используется элемент ListView с градиентной заливкой. Например, такое оформление интерфейса можно увидеть в списке контактов. Оказывается, совсем не сложно применить такую раскраску в своем приложении. Но для этого надо использовать стиль LVS_GRADIENT, как показано в листинге 4.7.

Листинг 4.7

using System.Runtime.InteropServices;


[DllImport("coredll.dll")]

static extern int SendMessage(IntPtr hwnd, uint msg, int wParam, int lParam);


const int LVS_EX_GRADIENT = 0x20000000;

const int LVM_SETEXTENDEDLISTVIEWSTYLE = 0x1000 + 54;


// Создаем градиентный фон для ListView

private void CreateGradientListView(ListView listView) {

 // Получим дескриптор ListView

 IntPtr hLV = listView.Handle;


 // Устанавливаем расширенный стиль

 SendMessage(hLV, (uint)LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_GRADIENT);

 // Обновляем вид

 listView.Refresh();

}


private void Form1_Load(object sender, EventArgs e) {

 CreateGradientListView(listView1);

}

Создание кнопки, содержащей изображение

В статье «How to: Create a Custom Image Button Control», которую можно отыскать по адресу msdn2.microsoft.com/en-us/library/ms172532(VS.80).aspx, описывается процесс создания кнопки, которая может содержать в качестве фона любое изображение. В первых версиях .NET Compact Framework кнопку вообще нельзя было сделать цветной, так как не существовало свойства BackColor. Потом данный недостаток был исправлен, но стандартными средствами пока не получится отобразить на кнопке рисунок. С помощью примера, который приводится в статье, можно обойти это ограничение.

Список с расширенными возможностями

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

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

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

Стивен Прата

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