Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Размер CPropertySheet под CPropertyPage. 
:(
    Опции темы
lv151
Дата 23.6.2009, 16:17 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 916
Регистрация: 11.2.2008

Репутация: нет
Всего: 2



Как  подогнать размер CPropertySheet под CPropertyPage?
PM MAIL   Вверх
Alca
Дата 23.6.2009, 21:50 (ссылка) |    (голосов:1) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 3993
Регистрация: 14.6.2006

Репутация: 6
Всего: 50



Цитата

Creating a Tabbed Dialog Box


The example in this section demonstrates how to create a dialog box that uses tabs to provide multiple pages of controls. The main dialog box is a modal dialog box. Each page of controls is defined by a dialog box template that has the WS_CHILD style. When a tab is selected, a modeless dialog box is created for the incoming page and the dialog box for the outgoing page is destroyed.
Note  In many cases, you can implement multiple-page dialog boxes more easily by using property sheets. For more information about property sheets, see About Property Sheets

The template for the main dialog box simply defines two button controls. When processing the WM_INITDIALOG message, the dialog box procedure creates a tab control and loads the dialog box template resources for each of the child dialog boxes.

The information is saved in an application-defined structure called DLGHDR. A pointer to this structure is associated with the dialog box window by using the SetWindowLong function. The structure is defined in the application's header file, as follows: 
#define C_PAGES 3 
 
Код

typedef struct tag_dlghdr { 
    HWND hwndTab;       // tab control 
    HWND hwndDisplay;   // current child dialog box 
    RECT rcDisplay;     // display rectangle for the tab control 
    DLGTEMPLATE *apRes[C_PAGES]; 
} DLGHDR; 

 

The following function processes the WM_INITDIALOG message for the main dialog box. The function allocates the DLGHDR structure, loads the dialog box template resources for the child dialog boxes, and creates the tab control.

The size of each child dialog box is specified by the DLGTEMPLATE structure. The function examines the size of each dialog box and uses the macro for the TCM_ADJUSTRECT message to calculate an appropriate size for the tab control. Then it sizes the dialog box and positions the two buttons accordingly. This example sends TCM_ADJUSTRECT by using the TabCtrl_AdjustRect macro.
Код

VOID WINAPI OnTabbedDialogInit(HWND hwndDlg) 
{ 
    DLGHDR *pHdr = (DLGHDR *) LocalAlloc(LPTR, sizeof(DLGHDR)); 
    DWORD dwDlgBase = GetDialogBaseUnits(); 
    int cxMargin = LOWORD(dwDlgBase) / 4; 
    int cyMargin = HIWORD(dwDlgBase) / 8; 
    TCITEM tie; 
    RECT rcTab; 
    HWND hwndButton; 
    RECT rcButton; 
    int i; 
 
    // Save a pointer to the DLGHDR structure. 
    SetWindowLong(hwndDlg, GWL_USERDATA, (LONG) pHdr); 
 
    // Create the tab control. 
    InitCommonControls(); 
    pHdr->hwndTab = CreateWindow( 
        WC_TABCONTROL, "", 
        WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, 
        0, 0, 100, 100, 
        hwndDlg, NULL, g_hinst, NULL 
        ); 
    if (pHdr->hwndTab == NULL) {
        // handle error
    }
 
    // Add a tab for each of the three child dialog boxes. 
    tie.mask = TCIF_TEXT | TCIF_IMAGE; 
    tie.iImage = -1; 
    tie.pszText = "First"; 
    TabCtrl_InsertItem(pHdr->hwndTab, 0, &tie); 
    tie.pszText = "Second"; 
    TabCtrl_InsertItem(pHdr->hwndTab, 1, &tie); 
    tie.pszText = "Third"; 
    TabCtrl_InsertItem(pHdr->hwndTab, 2, &tie); 
 
    // Lock the resources for the three child dialog boxes. 
    pHdr->apRes[0] = DoLockDlgRes(MAKEINTRESOURCE(DLG_FIRST)); 
    pHdr->apRes[1] = DoLockDlgRes(MAKEINTRESOURCE(DLG_SECOND)); 
    pHdr->apRes[2] = DoLockDlgRes(MAKEINTRESOURCE(DLG_THIRD)); 
 
    // Determine the bounding rectangle for all child dialog boxes. 
    SetRectEmpty(&rcTab); 
    for (i = 0; i < C_PAGES; i++) { 
        if (pHdr->apRes[i]->cx > rcTab.right) 
            rcTab.right = pHdr->apRes[i]->cx; 
        if (pHdr->apRes[i]->cy > rcTab.bottom) 
            rcTab.bottom = pHdr->apRes[i]->cy; 
    } 
    rcTab.right = rcTab.right * LOWORD(dwDlgBase) / 4; 
    rcTab.bottom = rcTab.bottom * HIWORD(dwDlgBase) / 8; 
 
    // Calculate how large to make the tab control, so 
    // the display area can accommodate all the child dialog boxes. 
    TabCtrl_AdjustRect(pHdr->hwndTab, TRUE, &rcTab); 
    OffsetRect(&rcTab, cxMargin - rcTab.left, 
            cyMargin - rcTab.top); 
 
    // Calculate the display rectangle. 
    CopyRect(&pHdr->rcDisplay, &rcTab); 
    TabCtrl_AdjustRect(pHdr->hwndTab, FALSE, &pHdr->rcDisplay); 
 
    // Set the size and position of the tab control, buttons, 
    // and dialog box. 
    SetWindowPos(pHdr->hwndTab, NULL, rcTab.left, rcTab.top, 
            rcTab.right - rcTab.left, rcTab.bottom - rcTab.top, 
            SWP_NOZORDER); 
 
    // Move the first button below the tab control. 
    hwndButton = GetDlgItem(hwndDlg, BTN_CLOSE); 
    SetWindowPos(hwndButton, NULL, 
            rcTab.left, rcTab.bottom + cyMargin, 0, 0, 
            SWP_NOSIZE | SWP_NOZORDER); 
 
    // Determine the size of the button. 
    GetWindowRect(hwndButton, &rcButton); 
    rcButton.right -= rcButton.left; 
    rcButton.bottom -= rcButton.top; 
 
    // Move the second button to the right of the first. 
    hwndButton = GetDlgItem(hwndDlg, BTN_TEST); 
    SetWindowPos(hwndButton, NULL, 
        rcTab.left + rcButton.right + cxMargin, 
        rcTab.bottom + cyMargin, 0, 0, 
        SWP_NOSIZE | SWP_NOZORDER); 
 
    // Size the dialog box. 
    SetWindowPos(hwndDlg, NULL, 0, 0, 
        rcTab.right + cyMargin + 
        2 * GetSystemMetrics(SM_CXDLGFRAME), 
        rcTab.bottom + rcButton.bottom + 2 * cyMargin + 
        2 * GetSystemMetrics(SM_CYDLGFRAME) + 
        GetSystemMetrics(SM_CYCAPTION), 
        SWP_NOMOVE | SWP_NOZORDER); 
 
    // Simulate selection of the first item. 
    OnSelChanged(hwndDlg); 
} 
 
// DoLockDlgRes - loads and locks a dialog box template resource. 
// Returns the address of the locked resource. 
// lpszResName - name of the resource 
 
DLGTEMPLATE * WINAPI DoLockDlgRes(LPCSTR lpszResName) 
{ 
    HRSRC hrsrc = FindResource(NULL, lpszResName, RT_DIALOG); 
    HGLOBAL hglb = LoadResource(g_hinst, hrsrc); 
    return (DLGTEMPLATE *) LockResource(hglb); 
} 

 

The following function processes the TCN_SELCHANGE notification message for the main dialog box. The function destroys the dialog box for the outgoing page, if any. Then it uses the CreateDialogIndirect function to create a modeless dialog box for the incoming page.
// OnSelChanged - processes the TCN_SELCHANGE notification. 
// hwndDlg - handle to the parent dialog box. 
 
Код

VOID WINAPI OnSelChanged(HWND hwndDlg) 
{ 
    DLGHDR *pHdr = (DLGHDR *) GetWindowLong( 
        hwndDlg, GWL_USERDATA); 
    int iSel = TabCtrl_GetCurSel(pHdr->hwndTab); 
 
    // Destroy the current child dialog box, if any. 
    if (pHdr->hwndDisplay != NULL) 
        DestroyWindow(pHdr->hwndDisplay); 
 
    // Create the new child dialog box. 
    pHdr->hwndDisplay = CreateDialogIndirect(g_hinst, 
        pHdr->apRes[iSel], hwndDlg, ChildDialogProc); 
} 

 

The following function processes the WM_INITDIALOG message for each of the child dialog boxes. You cannot specify the position of a dialog box created using the CreateDialogIndirect function. This function uses the SetWindowPos function to position the child dialog within the tab control's display area.
Код

// OnChildDialogInit - Positions the child dialog box to fall 
//     within the display area of the tab control. 
 
VOID WINAPI OnChildDialogInit(HWND hwndDlg) 
{ 
    HWND hwndParent = GetParent(hwndDlg); 
    DLGHDR *pHdr = (DLGHDR *) GetWindowLong( 
        hwndParent, GWL_USERDATA); 
    SetWindowPos(hwndDlg, HWND_TOP, 
        pHdr->rcDisplay.left, pHdr->rcDisplay.top, 
        0, 0, SWP_NOSIZE); 
} 




--------------------
PM WWW ICQ Skype Jabber   Вверх
lv151
Дата 24.6.2009, 08:59 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 916
Регистрация: 11.2.2008

Репутация: нет
Всего: 2



Согласен.  smile

Это сообщение отредактировал(а) lv151 - 24.6.2009, 09:00
PM MAIL   Вверх
Alca
Дата 24.6.2009, 10:46 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Завсегдатай
Сообщений: 3993
Регистрация: 14.6.2006

Репутация: 6
Всего: 50



Цитата

Использование класса CTabCtrl


Tab control - это мощное средство для решению многих проблем в интерфейсе приложений. Оно позволят существенно увеличить скорость работы вашего приложения, разбить на "части" диалог в удобной для пользователя форме. 

В MFC есть встроенный класс по работе с Tab control - класс CTabCtrl. 

Для практики напишем программу, которая будет использовать класс CTabCtrl и в которой будет три "закладки" - диалога. 

Шаги создания проекта: 

    1) Сначала создадим проект tab_control типа диалог.
    2) В редакторе ресурсов добавить Tab Control в шаблон диалога и назначим ему ID = IDC_TAB. 
    3) Используя ClassWizard, добавим переменную-член типа CTabCtrl со свойством Control.
    4) В OnInitDialog проинициализируем  необходимые переменные для CTabCtrl. 
    5) Используя ClassWizard, добавим обработку необходимых  сообщений от Tab control 'я. 
    6) Удалим за собой ненужные переменные.


Для начала сделайте первые три пункта, создайте переменную m_ctrTab класса CTabCtrl. После этого в функцие BOOL CTab_controlDlg::OnInitDialog() добавте следующее: 
    
Код

    ...

    TC_ITEM TabItem;
    TabItem.mask = TCIF_TEXT;
    TabItem.pszText = "Закладка1";    
    m_ctrTab.InsertItem( 0, &TabItem );
    TabItem.pszText = "Закладка2";
    m_ctrTab.InsertItem( 1, &TabItem );
    TabItem.pszText = "Закладка3";
    m_ctrTab.InsertItem( 2, &TabItem );

    ...



Это код инициализации Tab Control, мы создаём три закладки. Теперь нам надо, чтобы при нажатие на любую закладку, на экране появлялось то, что нам нужно. Самый простой вариант - это использовать на каждую закладку по диалогу - и потом просто в области Tab Control'а - выводить нужный диалог, в зависимости от текущей закладки. 

Сделаем это. Добавим три диалога в редакторе ресурсов и создадим каждому из них по классу - наследнику от CDialog. Назовем эти классы CPage1, CPage2 и CPage3( файлы Page1.cpp(h), Page2.cpp(h), Page3.cpp(h) ) . 

В свойствах этих трёх диалогов поставте Style как "Child" и Border как "none" - это очень важно, а в самих диалогах создайте какие либо элементы ( например, типа Static Text ), чтобы было видно отличие. 

Напишите эти три строчки в начале файла tab_controlDlg.cpp 

Код

    #include "Page1.h"
    #include "Page2.h"
    #include "Page3.h"


Продолжим в OnInitDialog:
Надо последовательно создать все страницы, причём указатели на них хранятся в самом m_ctrTab !!! В этом примере мы ипользовали lParam структуры TCITEM как хранилище указателя. Теперь переменные pPage1, pPage2 и pPage3 больше не нужны - указатели хранятся в надежном месте! Для каждой страницы вызывается метод ShowWindow() - для отображения первой, и скрытия остальных страниц. 

Код

    ...

    CPage1* pPage1;
    pPage1 = new CPage1; 
    TabItem.mask = TCIF_PARAM;
    TabItem.lParam = (LPARAM)pPage1; 
    m_ctrTab.SetItem(0, &TabItem);
    VERIFY(pPage1->Create(CPage1::IDD, &m_ctrTab));
    pPage1->SetWindowPos(NULL, 10, 30, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
    pPage1->ShowWindow(SW_SHOW); 
    
    CPage2* pPage2; 
    pPage2 = new CPage2;
    TabItem.mask = TCIF_PARAM; 
    TabItem.lParam = (LPARAM)pPage2;
    m_ctrTab.SetItem(1, &TabItem);
    VERIFY(pPage1->Create(CPage2::IDD, &m_ctrTab));
    pPage2->SetWindowPos(NULL, 10, 30, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
    pPage2->ShowWindow(SW_HIDE); 
    
    CPage3* pPage3; 
    pPage3 = new CPage3;
    TabItem.mask = TCIF_PARAM; 
    TabItem.lParam = (LPARAM)pPage3;
    m_ctrTab.SetItem(2, &TabItem);
    VERIFY(pPage1->Create(CPage3::IDD, &m_ctrTab));
    pPage3->SetWindowPos(NULL, 10, 30, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
    pPage3->ShowWindow(SW_HIDE);

    ...


Теперь добавим код по отображению текущей страницы и сокрытию предыдущей. Для этого добавим обработчики сообщений TCN_SELCHANGE и TCN_SELCHANGING : 

Код

void CTab_controlDlg::OnSelchangeTab(NMHDR* pNMHDR, LRESULT* pResult) 
{
    // TODO: Add your control notification handler code here
    
    int nTab = m_ctrTab.GetCurSel(); 
    TC_ITEM tci; 
    tci.mask = TCIF_PARAM; 

    m_ctrTab.GetItem(nTab, &tci); 
    ASSERT(tci.lParam); 

    CWnd* pWnd = (CWnd *)tci.lParam; 
    pWnd->ShowWindow(SW_HIDE); 


    *pResult = 0;
}

void CTab_controlDlg::OnSelchangingTab(NMHDR* pNMHDR, LRESULT* pResult) 
{
      int nTab = m_ctrTab.GetCurSel(); 
     TC_ITEM tci;
     tci.mask = TCIF_PARAM; 
    
     m_ctrTab.GetItem(nTab, &tci);
     ASSERT(tci.lParam); 
    
     CWnd* pWnd = (CWnd *)tci.lParam;
     pWnd->ShowWindow(SW_HIDE); 
    
     *pResult = 0;
}


Здесь используются те самые указатели, которые мы спрятали в OnInitDialog 

Теперь освободим память и разрушим диалоговые окна при выходе из приложения. 
Добавим функцию OnDestroy: 

Код

void CTab_controlDlg::OnDestroy()
{

    CDialog::OnDestroy();

    CWnd* pWnd;
    TC_ITEM tci;
    tci.mask = TCIF_PARAM; 

    for (int i = 2; i>=0; i--)
    {
        m_ctrTab.GetItem(i, &tci);
        ASSERT(tci.lParam); 

        pWnd = (CWnd *)tci.lParam;
        pWnd->DestroyWindow();
        delete pWnd;
    }
}


Ну вот и всё, приложение готово. 
Отсюда можно взять рабочую программу под MFC, с использованием CTabCtrl.




--------------------
PM WWW ICQ Skype Jabber   Вверх
voov
Дата 24.6.2009, 13:57 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Патамушта мы пилоты
**


Профиль
Группа: Участник
Сообщений: 460
Регистрация: 29.11.2007

Репутация: 8
Всего: 8



Alca, переключение табов не будет работать

Цитата(Alca @  24.6.2009,  10:46 Найти цитируемый пост)
void CTab_controlDlg::OnSelchangeTab(NMHDR* pNMHDR, LRESULT* pResult) 
{
........
    pWnd->ShowWindow(SW_HIDE); 
........
}

void CTab_controlDlg::OnSelchangingTab(NMHDR* pNMHDR, LRESULT* pResult) 
{
........
     pWnd->ShowWindow(SW_HIDE); 
........
}


PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Visual C++/MFC/WTL | Следующая тема »


 




[ Время генерации скрипта: 0.0706 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.