Форум программистов, компьютерный форум, киберфорум
C++ Builder
Войти
Регистрация
Восстановить пароль
 
Рейтинг 4.53/19: Рейтинг темы: голосов - 19, средняя оценка - 4.53
Технофашист
224 / 210 / 11
Регистрация: 11.03.2009
Сообщений: 886
1

Пара вопросов про Дочерние Окна

01.06.2011, 08:34. Просмотров 3403. Ответов 5
Метки нет (Все метки)


1) Как узнать какое из дочерних окон сейчас активно (в смысле на переднем плане под фокусом)?
2) При сворачивание модальных окно они сворачиваются в левый нижний угол. Как убрать это отображение свернутых окон? (ну чтоб сворачивались, но не видно было свёрнутых окон)
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
01.06.2011, 08:34
Ответы с готовыми решениями:

Пара вопросов
Добрий вечер форум! У меня пара вопросов: 1. Как сделать так чтоби форма ушла под другими окнами?...

Пара вопросов по Indy
Подскажите пожалуйста: 1. Как узнать, какая именно версия Инди стоит у меня в билдере? 2. Есть ли...

ifstream пара вопросов
ifstream in("a.in"); if (!in) { cout << "It`s impossible to open...

Пара вопросов о стиле
1. Используете ли вы префиксы? 2. именуете_так или ВсёЖеТак? 3. Если создаёте функцию для...

5
LK
Заблокирован
01.06.2011, 12:04 2
Создание многооконных приложения с дочерними окнами
Обрабатывайте событие OnClose для формы и выставляйте в нем параметр Action в caFree. Дело в том, что его значение по умолчанию для MDI Child форм =caMinimize. Кстати, если сделать Action := caNone, то форму нельзя будет закрыть.
и вот еще
MDI made easy

by Gerry Myers

While reading through several C++Builder online forums, I came across repeated questions concerning MDI (Windows Multiple Document Interface). I saw comments like, "How do I find the parent of my MDI child?" and "From whom do I derive my MDI child?" and "Why does my program crash when I close my MDI child?". I must admit that coming from Borland C++ (with OWL), I was also a little confused at first about C++Builder's handling of MDI. However, after some trial, error, and research, I realized that I was confused because it was so easy--too easy, apparently. C++Builder never ceases to amaze me with the simple way it handles form interaction. When you start working with MDI in C++Builder, forget everything you had to learn about the Document Manager, the document, and the view classes. In C++Builder land, all forms are created equal. In this article, we'll discuss how C++Builder creates MDI parents and children and passes information between them. If you're unfamiliar with the MDI concept, see "MDI 101" for an introduction.)

C++Builder MDI

If you've used C++Builder for more than five minutes, you're familiar with the TForm class. TForm contains properties for setting a window's color, border style, caption, and so on. In fact, you'll set almost any characteristic a window can have through the TForm base class. This symmetry isn't lost when it comes to C++Builder MDI windows.

Let's take a couple of minutes and have C++Builder create a new MDI application. To do so, choose File | New from the main menu, then select the Projects tab and double-click on the MDI Application icon. Now, take a look at the header files shown in Listings A and B for the main form (the parent) and the child form (TMDIChild). You'll notice that both are derived from TForm.

Listing A: TMainForm header, main.h
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class TMainForm : public TForm
{
__published:
   TMainMenu *MainMenu1;
   TMenuItem *File1;
   TMenuItem *FileNewItem;
   TMenuItem *FileOpenItem;
   TMenuItem *FileCloseItem;
   TMenuItem *Window1;
   TMenuItem *Help1;
   TMenuItem *N1;
   TMenuItem *FileExitItem;
   TMenuItem *WindowCascadeItem;
   TMenuItem *WindowTileItem;
   TMenuItem *WindowArrangeItem;
   TMenuItem *HelpAboutItem;
   TOpenDialog *OpenDialog;
   TMenuItem *FileSaveItem;
   TMenuItem *FileSaveAsItem;
   TMenuItem *Edit1;
   TMenuItem *CutItem;
   TMenuItem *CopyItem;
   TMenuItem *PasteItem;
   TMenuItem *WindowMinimizeItem;
   TPanel *SpeedPanel;
   TSpeedButton *OpenBtn;
   TSpeedButton *SaveBtn;
   TSpeedButton *CutBtn;
   TSpeedButton *CopyBtn;
   TSpeedButton *PasteBtn;
   TSpeedButton *ExitBtn;
   TStatusBar *StatusBar;
void __fastcall FormCreate(TObject *Sender);
   void __fastcall FileNewItemClick(TObject *Sender);
   void __fastcall WindowCascadeItemClick(
                   TObject *Sender);
   void __fastcall UpdateMenuItems(TObject *Sender);
   void __fastcall WindowTileItemClick(
                   TObject *Sender);
   void __fastcall WindowArrangeItemClick(
                   TObject *Sender);
   void __fastcall FileCloseItemClick(
                   TObject *Sender);
   void __fastcall FileOpenItemClick(
                   TObject *Sender);
   void __fastcall FileExitItemClick(
                   TObject *Sender);
   void __fastcall FileSaveItemClick(
                   TObject *Sender);
   void __fastcall FileSaveAsItemClick(
                   TObject *Sender);
   void __fastcall CutItemClick(TObject *Sender);
   void __fastcall CopyItemClick(TObject *Sender);
   void __fastcall PasteItemClick(TObject *Sender);
   void __fastcall WindowMinimizeItemClick(
                   TObject *Sender);
   void __fastcall FormDestroy(TObject *Sender);
private:
   void __fastcall CreateMDIChild(const String Name);
   void __fastcall ShowHint(TObject *Sender);
public:
   virtual __fastcall TMainForm(TComponent *Owner);
};
 
extern TMainForm *MainForm;
Listing B: TMDIChild header, childwin.h
C++
1
2
3
4
5
6
7
8
9
class TMDIChild : public TForm
{
__published:
   void __fastcall FormClose(TObject *Sender,
                   TCloseAction &Action);
private:
public:
   virtual __fastcall TMDIChild(TComponent *Owner);
};
You should also notice something strange: The new TMDIChild class is almost empty. I would have suspected that TMDIChild added special properties and methods for handling the required MDI tasks above and beyond the normal TForm capabilities. But no! As it turns out, all the MDI capabilities are built into the TForm class--non-MDI programs simply don't use them. It appears that some special child-related methods are added in the TMainForm (parent form) header, but they turn out to be simple menu-event handlers.

If all the MDI capabilities pre-exist in the TForm class, what triggers TForm to use them? This questions brings us back to the wonder of C++Builder. Click on your main form and look in the Object Inspector for the FormStyle property, as shown in Figure A.

Figure A: The parent window's FormStyle property is set to fsMDIForm.

It's set to fsMDIForm. Now click on the child form--its FormStyle property is set to fsMDIChild. That's all that's needed to turn a form into an MDI parent or an MDI child. Pretty neat!

C++Builder checks the FormStyle property during the form object's construction. It has only four possible values: fsMDIForm, fsMDIChild, fsNormal, and fsStayOnTop. For most standard forms, the value is fsNormal, which bypasses all MDI processes. When FormStyle is set to fsMDIForm or fsMDIChild, C++Builder establishes the structures that link the parent to the child.

MDI structures

Let's begin our exploration of MDI-related properties by examining ActiveMDIChild. This property (as well as the others we'll discuss) applies only to the parent form. ActiveMDIChild, which is of type TMDIChild*, points to the MDI child contained within the parent that holds focus. You can read it to get the active child form or set it to change the focus to a different child. The TForm class takes care of updating ActiveMDIChild as the user clicks between different child forms. The next property to be concerned with is MDIChildren, which is a list of all the child forms contained in the parent. The TForm class maintains this list for you, so there's nothing you need to do except use it. You probably shouldn't set or modify this list, since you can inadvertently lose child forms if you make a mistake. TForm maintains the list in the reverse order in which the child forms were created--element 0 points to the newest child form.

You can reference child forms directly from the MDIChildren list using bracket notation. For example, to get a pointer to the third-youngest child form, you'd write
C++
1
TMDIChild* mdiChild = MDIChildren[ 2 ];
The last property we'll discuss is MDIChildCount. It's of integer type and simply lets you know how many elements are in the MDIChildren list (how many child windows exist). I recommend that you only get this value. If you set it to an improper value, your program will either crash (if the value is larger than the number of actual child forms) or some child forms will be inaccessible (if the value is smaller than the actual number of child forms). It's safest to let the TForm class modify this value.

We've listed three parent form properties for accessing children, but how does the child form access the parent? Doing so turns out to be just as easy. You'll notice at the bottom of the main form's header file the statement
C++
1
extern TMainForm *MainForm;
This pointer is available to any class that includes the main form's header (which most forms do). Since the child class does include the main form's header, you can call the parent's methods and access the parent's properties simply through pointer reference. For example, if you want a child to grab focus, you can place the following statement somewhere in the child:
C++
1
MainForm->ActiveMDIChild = this;
Doing so will make the parent recognize the child as the active child.

Caution

As you can see, MDI applications in C++Builder are a snap. All the MDI capabilities are built right into the TForm base class, and you must learn only a handful of properties to manipulate the parent-child connection. With all this ease of use, I need to make one point clear. Remember how you normally create a component at runtime? For a button, you write code something like the following:
C++
1
2
3
TButton* btn;
btn = new TButton( this );
btn->Parent = this;
When you create a component, it needs to know its owner (this in the constructor) as well as its parent. The owner is the object responsible for deleting the component when the owner is destroyed. The parent is the object responsible for displaying the component (clipping, scrolling, moving, and so on). With most components, it's fine to set both the owner and the parent to the form onto which you're dropping them (this). However, this isn't the case with MDI children. When you create an MDI child, you should set only the owner (in the constructor statement)--don't worry about the parent. If you set the parent to this, everything will appear to work fine until you close the child window. At that point, your program will crash.

For example, the following code creates the child window with the application as the owner:
C++
1
2
3
TMDIChild* child;
child = new TMDIChild( Application );
child->Parent = this; // runtime error
That's fine. The error comes by setting the parent in the next line.

You'd expect to be required to set the Parent property of the child to point to the parent window (TMainForm), but this isn't the case. The TForm class takes care of the parent property the way it wants to, and that's just the way it is.

Conclusion

MDI applications were a little intimidating in the days of straight Windows programming and continued to be so with products like Borland's OWL and Microsoft's MFC. You had to be very familiar with the linkage between the parent and child as well as the document manager class. C++Builder has again made our programming lives easier: Now we have to make use of only three TForm properties to master MDI programming.
1
Технофашист
224 / 210 / 11
Регистрация: 11.03.2009
Сообщений: 886
01.06.2011, 13:08  [ТС] 3
Обрабатывайте событие OnClose для формы и выставляйте в нем параметр действий в caFree. Дело в том, что его значение по умолчанию для MDI Child форм = caMinimize. Кстати, если сделать действий: = caNone, то форму нельзя будет закрыть.
Я про это в курсе, вопрос в том, можно ли убрать отображение свернутого окна (под свернутым окном я подразумеваю то, что изображено на картинке).
Т.е. нужно чтобы я сворачивал окно и оно не отображалось свернутым. т.е. просто исчезало.
0
Изображения
 
LK
Заблокирован
01.06.2011, 13:42 4
Hide() не помогает ? и вы, по-моему, чего-то в настройках формы намудрили.

Добавлено через 2 минуты
это какая у вас система ? ХР с классической темой (стиль) , или что-нибудь более раннее ?
0
Технофашист
224 / 210 / 11
Регистрация: 11.03.2009
Сообщений: 886
01.06.2011, 13:57  [ТС] 5
XP с классической темой.

Чего то не понятно, где Hide() использовать?

Ну вот по стандарту жмешь свернуть окошко модальное, оно так сворачивается. я не против того что оно сворачивается, просто нужно чтобы оно на экране не оставалось даже в таком свёрнутом виде.
Т.е. я реализовываю некую панель задач.
Вот картинка, на ней моя панелька задач, всё работает, но вот эти "побочные" свёрнутые окна над моей панелькой задач, мне мешают
0
Миниатюры
Пара вопросов про Дочерние Окна  
LK
Заблокирован
01.06.2011, 14:50 6
OnMinimize
C++
1
ИмяВашейФормы->Hide();
шо-то-вы-мутите-с-этими-панелями...
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
01.06.2011, 14:50

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

Пару вопросов про TChart
Здраствуйте, Возник вопрос по поводу названия параметра в TChart(Series), которые отвечает за...

Параметры области, в которой "живут" дочерние окна
Имеется MDI-приложение. Нужно выяснить ширину и высоту области окна, в которой живут дочерние окна....

Пара вопросов про сателиты...
1. Сколько сайтов(максимум) лучше делать на одном IP? 2. Хочу их разместить у одного провайдера,...

пара вопросов про OC4J
У меня пара вопросов про OC4J. 1) Я развернул там .ear, пытаюсь зайти на страницу web-модуля...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin® Version 3.8.9
Copyright ©2000 - 2021, vBulletin Solutions, Inc.