Читаем Developing a GUI in C++ and DirectX полностью

As for drawing the columns and items… I decided that I’d like to have absolute control over how each individual item/column in the listbox was drawn. Towards this end, I decided to have the listbox draw its items and columns by repeatedly calling two virtual functions, gui_listbox_item::draw() and gui_listbox_column::draw(). Each function took one parameter - a rectangle understood to be the location on the screen where the column or item was supposed to be drawn. The default implementations of these draw() functions just spit out the text associated with that particular column and subitem in that rectangle; however, I could now easily derive and override draw() for items or columns that required a unique appearance. This technique has seemed to work for me so far, though I don’t claim that it’s the best or “right” way to do it.

Drawing the items required a little more work than the columns, however. Items had to be drawn with or without a highlight, depending on whether they were selected or not. Not a big deal, but important to remember.

Then there’s the issue of scrollbars. My report-view listbox contained two members, m_horzscrollbar and m_vertscrollbar, both GUI scrollbars. Whenever the size of the listbox was changed (wm_sizechanged()), it took a peek at the width and height of the data it had, and either displayed or hid the scrollbars as appropriate.

It’s been a whirlwind tour, but hopefully you have a general idea of what lies ahead of you in your quest to create controls for your GUI. The only thing I want to reiterate is “style is fun.” Don’t be afraid to take a few liberties as you create your GUI - implement the stuff you’ve always wished for, and the stuff that makes the most sense in your game. This is especially important if the game your making relies heavily on the functionality of your GUI - like, say, you’re making a RTS game.

But also remember that in creating your controls, your doing the same balancing act as with the rest of your game - you’re weighing features against development time. Give your players as easy and intuitive GUI as possible, but also, don’t spend all your time making 50 different controls. You want to strike a balance between functionality, the good thing, and complexity, the bad thing.

<p>Part IV: Resource Editors and Other Madness</p>

This section will address a whole bunch of miscellaneous issues and ideas to polish off your game GUI.

<p>Saving Windows</p>

Window serialization (or, saving and loading windows) may or may not be crucial for your project. If your game GUI is minimal, you might be able to get by with just hard-coding the windows into your game. But if your GUI’s more complex than that, you’re going to want code that will save a window (and all its children) to a file, and then load it back up again. For starters, having window serialization code allows you to change your game’s GUI without recompiling, and is a boon if you’re working with more than one person. So, let’s spend a little time talking about how I implemented saving windows.

My plan of attack was easy - start at the main dialog window, and recursively go through all of its child windows, saving each one to disk. If I were programming in C, the first thing I would have said to myself would have been “OK, so if I have to save these windows, I need a byte for each window that tells me what type of window it is, so I can load it back up correctly. 1 is a button, 2 is a listbox, 3 is an icon, etc.”

This kind of problem is specifically what C++’s RTTI (Run Time Type Identification) addresses. RTTI provides two things, a type_info class and a typeid() function, which together allowed me to query an object for it’s class name - “gui_window”, “gui_button”, etc. Instead of fiddling with enums and IDs, I simply call typid() for each window I’m going to save, and “write down” the class name of the window.

I saw two minor disadvantages to using RTTI’s object identification functions to help save windows. First of all, the RTTI IDs are strings, not integers, which means they’ll take up more space on disk (store them Pascal style, that is, the first 4 bytes describe the length of the string, followed by the string data itself). Second, if you change the name of one of your window classes, you’ll break any window files that you’ve previously saved. For these reasons, you might opt out of using RTTI in this manner - after all, just because a technology is there doesn’t mean you have to use it. However, I found RTTI to be a lifesaver in my code.

For more information on RTTI and these two functions, search for them in your online help. Also, if you decide to use RTTI with Visual C++, make sure you turn it on in your project settings, C/C++ tab, C++ language option.

<p>Loading Windows</p>

Loading windows is more difficult than saving them, primarily because you have to new each window, load it up, and then remember to delete it when it’s no longer needed.

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

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

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

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