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

private void textBox1_KeyUp(object sender, KeyEventArgs e) {

 if (e.KeyCode == Keys.Enter) textBox2.Focus();

}


private void textBox2_KeyUp(object sender, KeyEventArgs e) {

 if (e.KeyCode = Keys.Enter) textBox3.Focus();

}


private void textBox3_KeyUp(object sender, KeyEventArgs e) {

 if (e.KeyCode == Keys.Enter) textBox1.Focus();

}

Управление полосой прокрутки

При отображении большого текста пользователь может применять полосу прокрутки для перемещения по тексту. Разработчик может использовать сообщение WM_VScroll для программного управления полосой прокрутки. Например, можно использовать этот механизм для создания эффекта автоматической прокрутки текста.

Для иллюстрации примера нужно расположить на форме текстовое поле и отобразить в нем какой-нибудь длинный текст. В примере используется отрывок из произведения А. Пушкина «Дубровский». Также на форме надо расположить четыре кнопки, при помощи которых пользователь сможет управлять отображением текста, прокручивая его на одну строчку или страницу вниз и вверх. В листинге 4.2 приведен код, который реализует описанный способ отображения текста.

Листинг 4.2

[DllImport("coredll.dll")]

extern static int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);


///

/// Сообщение Windows для работы с полосой прокрутки

///

const int WM_VSCROLL = 0x115;


// константы для сообщения WM_VSCROLL

const int SB_LINEUP = 0:

const int SB_LINEDOWN = 1;

const int SB_PAGEUP = 2;

const int SB_PAGEDOWN = 3;


private void Form1_Load(object sender, EventArgs e) {

 // Отрывок из повести А.С.Пушкина "Дубровский"

 txtBook.Text = @"Несколько лет тому назад в одном из своих

 поместий жил старинный русский барин, Кирила Петрович Троекуров.

 Его богатство, знатный род и связи давали ему большой вес в губерниях,

 где находилось его имение. Соседи рады были угождать малейшим его

 прихотям; губернские чиновники трепетали при его имени; Кирила

 Петрович принимал знаки подобострастия как надлежащую дань; дом его

 всегда был полон гостями, готовыми тешить его барскую праздность,

 разделяя шумные, а иногда и буйные его увеселения.";

}


private void butUp_Click(object sender, EventArgs e) {

 // на одну строчку вверх

 SendMessage(txtBook.Handle, WM_VSCROLL, SB_LINEUP, 0);

}


private void butDown_Click(object sender, EventArgs e) {

 // на одну строчку вниз

 SendMessage(txtBook.Handle, WM_VSCROLL, SB_LINEDOWN, 0);

}


private void butPageUp_Click(object sender, EventArgs e) {

 // на одну страницу вверх

 SendMessage(txtBook.Handle, WM_VSCROLL, SB_PAGEUP, 0);

}


private void butPageDown_Click(object sender, EventArgs e) {

 // на одну страницу вниз

 SendMessageCtxtBook.Handle, WM_VSCROLL, SB_PAGEDOWN, 0);

}

Внешний вид приложения показан на рис. 4.1.

Рис. 4.1. Программная прокрутка текста

Многострочный текст в кнопке

По умолчанию текст для кнопок может содержать только одну строку. Но при желании можно изменить этот стиль с помощью функций GetWindowLong и SetWindowLong, как показано в листинге 4.3.


Листинг 4.3

[DllImport("coredll.dll")]

private static extern IntPtr GetCapture();


[DllImport("coredll.dll")]

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

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

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

Стивен Прата

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