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

 //txtEditor.Height = this.Height;

 SetTextBoxHeight();

}


// устанавливаем размеры текстового поля в зависимости от

// активности SIP

private void SetTextBoxHeight() {

 if (SIP.Enabled)

  txtEditor.Height = SIP.VisibleDesktop.Height + 2;

 else

  txtEditor.Height = this.Height;

}


private void SIP_EnabledChanged(object sender, EventArgs e) {

 SetTextBoxHeight();

}

Стандартные операции с текстом

На данной стадии уже создан первый прототип приложения. После запуска программы пользователь может вводить и удалять текст с помощью SIP. Но этого недостаточно для комфортной работы с текстом.

Пользователь должен иметь возможность манипулировать текстом, то есть копировать часть текста, вырезать его, удалять и вставлять в нужную позицию. Для этого надо создать меню при помощи элемента mainMenu. В подменю Правка надо добавить стандартные команды редактирования текста — Отменить, Вырезать, Копировать, Вставить. Если бы приложение создавалось для среды исполнения .NET Compact Framework 2.0, то можно было бы использовать класс Clipboard. Но так как используется .NET Compact Framework 1.0, то придется обратиться к функциям Windows API и использовать неуправляемый код, что иллюстрирует листинг 7.32.

Листинг 7.32

// сообщения буфера обмена

public const int WM_CUT = 0x0300;

public const int WM_COPY = 0x0301;

public const int WM_PASTE = 0x0302;

public const int WM_CLEAR = 0x0303;

public const int WM_UNDO = 0x0304;


// функции API

[DllImport("coredll.dll", CharSet = CharSet.Unicode)]

public static extern IntPtr GetFocus();

[DllImport("coredll.dll")]

public static extern int SendMessage(IntPtr hWnd, uint Message,

 uint wParam, uint lParam);


private void mnuCut_Click(object sender, EventArgs e) {

 // Вырезаем текст

 SendMessage(hwndEditor, WM_CUT, 0, 0);

}


private void mnuUndo_Click(object sender, EventArgs e) {

 // Отменяем последнее действие

 SendMessage(hwndEditor, WM_UNDO, 0, 0);

}


private void mnuCopy_Click(object sender, EventArgs e) {

 // Копируем выделенный текст

 SendMessage(hwndEditor, WM_COPY, 0, 0);

}


private void mnuPaste_Click(object sender, EventArgs e) {

 // Вставляем текст из буфера обмена

 SendMessage(hwndEditor, WM_PASTE, 0, 0);

}


private void mnuDelete_Click(object sender, EventArgs e) {

 // Удаляем выделенный текст

 SendMessage(hwndEditor, WM_CLEAR, 0, 0);

}

Теперь необходимо добавить в создаваемое приложение поддержку контекстного меню. Использование контекстного меню избавит пользователя от необходимости постоянно переводить стилус в нижнюю часть экрана для доступа к командам меню. В программу нужно добавить элемент управления ContextMenu и сделать список команд меню, который будет дублировать подпункт основного меню Правка. Созданное контекстное меню надо связать с текстовым полем при помощи свойства ContextMenu. Осталось только скопировать код из команд основного меню в соответствующие места для команд контекстного меню. Например, для команды контекстного меню Копировать надо использовать код, приведенный в листинге 7.33.

Листинг 7.33

private void cmenuCopy_Click(object sender, EventArgs e) {

 // Копируем выделенный текст

 SendMessage(hwndEditor, WM_COPY, 0, 0);

}

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

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

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

Стивен Прата

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