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

private static extern int GetWindowLong(IntPtr hWnd, int nIndex);


[DllImport("coredll.dll")]

private static extern int SetWindowLong(IntPtr hWnd, int nIndex,

 int dwNewLong);


public const int GWLSTYLE = -16;


// стиль многострочного текста

public const int BS_MULTILINE = 0x2000;


private void Form1_Load(object sender, EventArgs e) {

 IntPtr hWnd;

 int style;

 this.butMultiline.Capture = true;

 hWnd = GetCapture();

 this.butMultiline.Capture = false;

 style = GetWindowLong(hWnd, GWL_STYLE);

 SetWindowLong(hWnd, GWL_STYLE, style | BS_MULTILINE);

}

В этом примере для сравнения использовались две кнопки. На каждой из них размещен достаточно длинный текст (рис. 4.2).

Рис. 4.2. Вид кнопок в процессе программирования

При загрузке формы выполняется изменение стиля для первой кнопки butMultiline, а вторая кнопка остается без изменений. После запуска приложения можно заметить, что длинный текст в первой кнопке разбивается на две строки и полностью умещается в границах кнопки. Во второй кнопке слова обрезаются, и текст просто нельзя прочитать (рис. 4.3).

Рис. 4.3. Создание многострочного текста на кнопке

ВНИМАНИЕ

Данный пример был написан еще для .NET Compact Framework 1.0. В .NET Compact Framework 2.0 нет надобности вызывать функцию GetCapture() для получения дескриптора hWnd, так как теперь поддерживается свойство Control.Handle.

Увеличение ширины выпадающего списка ComboBox

Выпадающий список у комбинированного окна равен ширине самого комбинированного окна ComboBox. Но можно обойти это ограничение с помощью неуправляемого кода, как показано в листинге 4.4.

Листинг 4.4

///

/// Сообщение, получающее размеры выпадающего списка

/// комбинированного окна

///

const int CB_GETDROPPEDWIDTH = 0x015f;


///

/// Сообщение, устанавливающее размеры выпадающего списка

/// комбинированного окна

///

const int CB_SETDROPPEDWIDTH = 0x0160;


[DllImport("coredll.dll")]

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


private void Form1_Load(object sender, EventArgs e) {

 comboBox1.Items.Add("Раз");

 comboBox1.Items.Add("Два");

 comboBox1.Items.Add("Три");


 comboBox2.Items.Add("Длинный текст");

 comboBox2.Items.Add("Очень длинный текст");

 comboBox2.Items.Add("Hy очень длинный текст");

 // Устанавливаем желаемую ширину

 SendMessage(comboBox2.Handle, CB_SETDROPPEDWIDTH, 200, 0);


 // Получим ширину выпадающего окна

 int retval = SendMessage(comboBox2.Handle, CB_GETDROPPEDWIDTH, 0, 0);

 this.Text = retval.ToString();

}

На форме надо разместить два элемента ComboBox. Один из них будет стандартным. А второй элемент обработает сообщение CB_SETDROPPEDWIDTH со значением второго параметра 200. В результате выпадающий список будет в ширину занимать 200 пикселов.

После запуска программы сначала надо обратить внимание на работу первого комбинированного окна (рис. 4.4). Оно ведет себя стандартным образом.

Рис. 4.4. Стандартный размер выпадающего списка

Теперь нужно перейти ко второму комбинированному окну. У него размер выпадающего списка увеличился, что позволяет увидеть весь текст (рис. 4.5).

Рис. 4.5. Увеличенный размер выпадающего списка у ComboBox

ListBox

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

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

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

Стивен Прата

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