기본 콘텐츠로 건너뛰기

[code project 펌]Hacking the CPropertySheet

출처 돼지스머프 | 돼지스멒
원문 http://blog.naver.com/bbk1999/90001777342

Hacking the CPropertySheet

By Mustafa Demirhan

Introduction

In my applications, I usually need to change the default look and feel and the behavior of Property Sheets.
Working with property sheets and pages is really a pain and you must do most of the work on yourself for non-standard operations
(such as changing the coordinates of the buttons, adding new controls to the property sheet, ...etc).
In this article, I tried to give as many tips and tricks as I can do.
Before going in to the details, you should first create a CPropertySheet derived class - say CMyPropSheet.

Lets begin with some simple things:

Hiding Standards Buttons

When our property sheet shows up, by default it has all the buttons visible and the Apply button is disabled.
In general we don't need to use Apply button. To hide the apply button, you can simply use the following code:
propsheet.m_psh.dwFlags |= PSH_NOAPPLYNOW;
However, this does not work for all buttons. A better approach is to get a handle to the specified button and then threat the button as a normal window.
Here is a sample code that hides the cancel button:
CWnd *pWnd = GetDlgItem( IDCANCEL );
pWnd->ShowWindow( FALSE );
When we hide the controls using the ShowWindow function all the other controls remain whereever they were.
This may give the property sheet and unappealing look. To avoid this, we should reposition the controls manually.
Next subsections shows how to move the controls.

Moving the Standard Buttons

As I mentioned before, once we get the handle to the standard buttons, we can treat them like any other window.
The code below first hides Apply and Help buttons, then moves OK and Cancel buttons right.
BOOL CMyPropSheet::OnInitDialog () 
{
    BOOL bResult = CPropertySheet::OnInitDialog();
 
    int ids [] = {IDOK, IDCANCEL};//, ID_APPLY_NOW, IDHELP };

    // Hide Apply and Help buttons
    CWnd *pWnd = GetDlgItem (ID_APPLY_NOW);
    pWnd->ShowWindow (FALSE);
    pWnd = GetDlgItem (IDHELP);
    pWnd->ShowWindow (FALSE);
    
    CRect rectBtn;
    int nSpacing = 6;        // space between two buttons...
 
    for( int i =0; i < sizeof(ids)/sizeof(int); i++)
    {
        GetDlgItem (ids [i])->GetWindowRect (rectBtn);
        
        ScreenToClient (&rectBtn);
        int btnWidth = rectBtn.Width();
        rectBtn.left = rectBtn.left + (btnWidth + nSpacing)* 2;
        rectBtn.right = rectBtn.right + (btnWidth + nSpacing)* 2;
 
        GetDlgItem (ids [i])->MoveWindow(rectBtn);
    }
    
    return bResult;
}
The following code moves all standard buttons to the right and resizes the property sheet appropriately.
BOOL CMyPropSheet::OnInitDialog () 
{
    BOOL bResult = CPropertySheet::OnInitDialog();
    
    int ids[] = { IDOK, IDCANCEL, ID_APPLY_NOW };
    
    CRect rectWnd;
    CRect rectBtn;
    
    GetWindowRect (rectWnd);
    GetDlgItem (IDOK)->GetWindowRect (rectBtn);
    
    int btnWidth = rectBtn.Width();
    int btnHeight = rectBtn.Height();
    int btnOffset = rectWnd.bottom - rectBtn.bottom;
    int btnLeft = rectWnd.right - rectWnd.left;
 
    rectWnd.bottom = rectBtn.top;
    rectWnd.right = rectWnd.right + btnWidth + btnOffset;
    MoveWindow(rectWnd);
    
    rectBtn.left = btnLeft;
    rectBtn.right = btnLeft + btnWidth;
 
    for (int i = 0; i < sizeof (ids) / sizeof (int); i++)
    {
        rectBtn.top = (i + 1) * btnOffset + btnHeight * i;
        rectBtn.bottom = rectBtn.top + btnHeight;
        GetDlgItem (ids [i])->MoveWindow (rectBtn);
    }
    
    return bResult;
}

Changing the Tab Label

To change the labels at runtime, we just need to get a pointer to the tab control and then use SetItem functions of the tab control.
Here is an example:
TC_ITEM item;
item.mask = TCIF_TEXT;
item.pszText = "New Label";
 
//Change the label of the first tab (0 is the index of the first tab)...
GetTabControl ()->SetItem (0, &item);

Changing the Tab Label Font

This is also similar to changing the label of the tab. Here is an example code:
m_NewFont.CreateFont (14, 0, 0, 0, 800, TRUE, 0, 0, 1, 0, 0, 0, 0, _T("Arial") );
GetTabControl()->SetFont (&m_NewFont);

Using Images with Tab Labels

In order to use images with the tab labels, first you have to create a CImageList class with the images you want to use in the tab control.
The using SetItem method of CTabCtrl class, you should set the images of the items. Here is an example:
BOOL CMyPropSheet::OnInitDialog ()
{
    BOOL bResult = CPropertySheet::OnInitDialog();
 
    m_imageList.Create (IDB_MYIMAGES, 13, 1, RGB(255,255,255));
    CTabCtrl *pTabCtrl = GetTabControl ();
    pTabCtrl->SetImageList (&m_imageList);
    
    TC_ITEM item;
    item.mask = TCIF_IMAGE;
    for (int i = 0; i < NUMBER_OF_TABS; i++)
    {
        item.iImage = i;
        pTabCtrl->SetItem (i, &item );
    }
 
    return bResult;
}

Placing a Bitmap in the Property Sheet

The following code places a bitmap in the left-bottom corner of the property sheet.
void CMyPropSheet::OnPaint () 
{
    CPaintDC dc(this); // device context for painting
    
    int nOffset = 6;
    // load IDB_BITMAP1 from our resources
    CBitmap bmp;
    if (bmp.LoadBitmap (IDB_BITMAP1))
    {
        // Get the size of the bitmap
        BITMAP bmpInfo;
        bmp.GetBitmap (&bmpInfo);
        
        // Create an in-memory DC compatible with the
        // display DC we're using to paint
        CDC dcMemory;
        dcMemory.CreateCompatibleDC (&dc);
        
        // Select the bitmap into the in-memory DC
        CBitmap* pOldBitmap = dcMemory.SelectObject (&bmp);
        
        // Find a bottom-left point for the bitmap in the client area
        CRect rect;
        GetClientRect (&rect);
        int nX = rect.left + nOffset;
        int nY = rect.top + (rect.Height () - bmpInfo.bmHeight) - nOffset;
        
        // Copy the bits from the in-memory DC into the on-
        // screen DC to actually do the painting. Use the centerpoint
        // we computed for the target offset.
        dc.BitBlt (nX, nY, bmpInfo.bmWidth, bmpInfo.bmHeight, &dcMemory, 
            0, 0, SRCCOPY);
        
        dcMemory.SelectObject (pOldBitmap);
    }
 
    // Do not call CPropertySheet::OnPaint() for painting messages
}

Adding a Control to the Property Sheet

To add your own control to the property sheet, first add a member variable to your header class.
The following steps shows you adding an Edit conrol to your property sheet (to the bottom-left corner): In MyPropSheet.h:
public:
    CEdit m_edit;
In MyPropSheet.cpp:

BOOL CMyPropSheet::OnInitDialog ()
{
    BOOL bResult = CPropertySheet::OnInitDialog ();
    
    CRect rect;
    
    int nHeight = 24;
    int nWidth = 120;
    int nOffset = 6;
    
    GetClientRect (&rect);
 
    // Find a bottom-left point for the edit control in the client area
    int nX = rect.left + nOffset;
    int nY = rect.top + (rect.Height() - nHeight) - nOffset;
    
    // finally create the edit control
    m_Edit.CreateEx (WS_EX_CLIENTEDGE, _T("EDIT"), NULL,
                     WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER, 
        nX, nY, nWidth, nHeight, m_hWnd, 0, 0 );
 
    return bResult;
}

A More Complex Scenario

Now we are ready for a more complex operation on these stupid property sheets.
Suppose you want to add a header on top of your property sheet.
At first, this seems to be an easy task, but when you implement the first thing in your mind, you would mostly be disappointed.
You need a free space on top of the property sheet.
Thus you need to increase the size of the property sheet, then move all the buttons and tab control.
However this is not enough. The problem is that, when you move your Tab Control, your property pages in the Tab Control will not be moved appropriately.
They will remain on the same coordinates (even though the tab control is moved).
So, you also have to move the first property page on your tab control.
You don't have to move the other property pages, because when you change the active tab, tab control will get the new coordinates automatically and place the property pages correctly.
The problem occurs only when the property sheet is created and firstly shown.
The code below creates an area on top of the property sheet and moves all the controls and property pages accordingly.
You just need to add your header control.
BOOL CMyPropSheet::OnInitDialog ()
{
    BOOL bResult = CPropertySheet::OnInitDialog ();
 
    
    int _PropSheetButtons[] = {IDOK, IDCANCEL, ID_APPLY_NOW, IDHEL };
    int m_nHeaderHeight = 70;        //The height of the header control
 
    CRect rectWnd;
    GetWindowRect (rectWnd);
    ScreenToClient (rectWnd);
    SetWindowPos (NULL, 0, 0, rectWnd.Width(), 
        rectWnd.Height() + m_nHeaderHeight,
        SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
    
    // create your header control here
    //m_HeaderCtrl.CreateEx (NULL, NULL, NULL, 
    //    WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER, 
    //    -1, -1, rectWnd.Width (), m_nHeaderHeight - 5, m_hWnd, 0, 0);
    //m_HeaderCtrl.SetTitle (m_sTitle);
    //m_HeaderCtrl.SetIcon (m_nIcon);
    //m_HeaderCtrl.SetDesc (m_sDesc);*/
    
    
    HWND hWnd = (HWND)GetTabControl ()->m_hWnd;
    ASSERT (hWnd != NULL);
    CRect rectOld;
    ::GetWindowRect (hWnd, &rectOld);
    ScreenToClient (&rectOld);
    ::SetWindowPos (hWnd, NULL, rectOld.left, 
                    rectOld.top + m_nHeaderHeight, rectOld.Width (), 
                    rectOld.Height (),
                    SWP_NOZORDER | SWP_NOACTIVATE);
    
    hWnd = (HWND)m_Page1.m_hWnd; // m_Page1 is assumed to be the first page
                 // in your property sheet. de corrections accordingly
 
    ASSERT (hWnd != NULL);
    ::GetWindowRect (hWnd, &rectOld);
    ScreenToClient (&rectOld);
    ::SetWindowPos (hWnd, NULL, rectOld.left, 
                    rectOld.top + m_nHeaderHeight, 
                    rectOld.Width (), rectOld.Height (),
                    SWP_NOZORDER | SWP_NOACTIVATE);
    
    // move buttons by similar amount
    for (int i = 0; i < sizeof (_PropSheetButtons) / sizeof (int); i++)
    {
        hWnd = ::GetDlgItem (m_hWnd, _PropSheetButtons [i]);
        if (hWnd != NULL)
        {
            ::GetWindowRect (hWnd, &rectOld);
            ScreenToClient (&rectOld);
            ::SetWindowPos (hWnd, NULL, rectOld.left, 
                            rectOld.top + m_nHeaderHeight, 
                            rectOld.Width (), rectOld.Height (),
                            SWP_NOZORDER | SWP_NOACTIVATE);
        }
    }
    
    // Enable Apply Now button
    hWnd = ::GetDlgItem(m_hWnd, ID_APPLY_NOW);
    if (hWnd != NULL)
    {
        ::ShowWindow (hWnd, SW_SHOW);
        ::EnableWindow (hWnd, TRUE);
    }
    
    CenterWindow ();
    
    return bResult;
}
So far so good. Now, I want to change the behavior for the OK, Cancel and Apply buttons.
For example, when the user clicks on OK or Cancel button, you may want to do something different rather than closing the property sheet.
Here is a general template that can be used to do this kind of stuff:
BOOL CMyPropSheet::OnCommand (WPARAM wParam, LPARAM lParam) 
{
    // allow message map override
    if (CWnd::OnCommand (wParam, lParam))
        return TRUE;
    
    // crack message parameters
    UINT nID = LOWORD(wParam);
    HWND hWndCtrl = (HWND)lParam;
    int nCode = HIWORD(wParam);
    
    // set m_nModalResult to ID of button, whenever button is clicked
    if (hWndCtrl != NULL && nCode == BN_CLICKED)
    {
        if (::SendMessage(hWndCtrl, WM_GETDLGCODE, 0, 0) &
            (DLGC_BUTTON|DLGC_DEFPUSHBUTTON))
        {
            LONG lStyle = ::GetWindowLong(hWndCtrl, GWL_STYLE) & 0x0F;
            if (lStyle == BS_PUSHBUTTON || lStyle == BS_DEFPUSHBUTTON ||
                lStyle == BS_USERBUTTON || lStyle == BS_OWNERDRAW)
            {
                if (nID == IDOK)
                {
                    if (YOU_WANT_TO_CLOSE_THE_PROPERTY_SHEET)
                    {
                        // do whatever you want before closing the property page
 
                        // You dont have to assign nID to 
                        // m_nModalResult. If you want to 
                        // return IDOK or IDCANCEL instead of 
                        // the default return value, 
                        // you can do it by assigning IDOK or 
                        // IDCANCEL to m_nModalResult
                        m_nModalResult = nID;
                    }
                    else
                    {
                        // do whatever you want.
                        return TRUE;
                    }
                }
                else if (nID == ID_APPLY_NOW)
                {
                    if (YOU_WANT_TO_CLOSE_THE_PROPERTY_SHEET)
                    {
                        // do whatever you want before 
                        // closing the property page
                        
                        // You dont have to assign nID to 
                        // m_nModalResult. If you want to 
                        // return IDOK or IDCANCEL instead 
                        // of the default return value, 
                        // you can do it by assigning IDOK or 
                        // IDCANCEL to m_nModalResult
                        m_nModalResult = nID;
                    }
                    else
                    {
                        // do whatever you want.
                        return TRUE;
                    }
                }
                else if (nID == IDCANCEL)
                {
                    if (YOU_WANT_TO_CLOSE_THE_PROPERTY_SHEET)
                    {
                        // do whatever you want before 
                        // closing the property page
 
                        // You dont have to assign nID to 
                        // m_nModalResult. If you want to 
                        // return IDOK or IDCANCEL instead 
                        // of the default return value, 
                        // you can do it by assigning IDOK or 
                        // IDCANCEL to m_nModalResult
                        m_nModalResult = nID;
                    }
                    else
                    {
                        // do whatever you want.
                        return TRUE;
                    }
                }
            }
        }
    }
    return FALSE;
}

댓글

이 블로그의 인기 게시물

80040154 오류로 인해 CLSID가 {xxxx-...}인 구성 요소의 COM 클래스 팩터리를 검색하지 못했습니다.

원문보기 .NET 으로 만든 응용프로그램에서 com 객체를 호출한 경우 Windows7 64bit 에서 제목과 같은 에러가 발생했다. Win32 COM 과 .NET 프로그램간의 호환성 때문에 생긴 문제였다. 원인은 .NET 실행시 JIT 컴파일러에 의해 최적화된 기계어로 변환되기 때문.. Win32 COM은 컴파일시.. Win32 COM에 맞춰 빌드 속성에서 하위버전으로 맞춰 컴파일을 다시하는 방법도 있지만 메인 프로젝트가 .NET이라면 참조되는 모든 프로젝트를 다 바꿔야할 노릇.. 또 다른 방법은 COM+를 이용하여 독립적으로 만드는 것이다. 분리시키는 방법은 아래 주소해서 확인할 수 있다. http://support.microsoft.com/kb/281335 나의 경우는 Win32 COM DLL을 64비트 .NET 프로그램에서 참조하니 COM 객체를 제대로 호출하지 못하였습니다. 그래서 .NET 프로그램의 Target Machine을 x86으로 설정하니 제대로 COM 객체를 호출하였습니다.

[Pyinstaller] 실행 파일 관리자 권한 획득하기

고객사에서 일부 사용자에게서 프로그램 오류가 발생한다며 아래와 같이 에러 캡처를 보내왔습니다. 프로그램에서 로그를 남기기 위해 로그 파일을 생성하는데 권한의 문제로 로그 파일을 생성하지 못해 프로그램 오류가 발생한 것 같습니다. 처음에는 Python 코드에서 관리자 권한을 요청하는 코드를 넣으려고 했는데, 실제로 Stackoverflow를 찾아보면 이런 내용이 나옵니다. 프로그램이 관리자 권한으로 실행되지 않았다면 관리자 권한으로 다시 프로그램을 실행시키는 코드입니다. import os import sys import win32com.shell.shell as shell ASADMIN = 'asadmin' if sys.argv[-1] != ASADMIN: script = os.path.abspath(sys.argv[0]) params = ' '.join([script] + sys.argv[1:] + [ASADMIN]) shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params) sys.exit(0) 하지만 개인적으로 이런 방식은 마음에 들지 않았고 조금 더 찾아보니 Pyinstaller로 exe 파일을 만들 때 옵션을 설정하여 관리자 권한을 요청하도록 할 수 있다고 합니다. --uac-admin을 옵션에 추가하면 프로그램 실행 시 관리자 권한을 요청할 수 있습니다. pyinstaller.exe --uac-admin sample.py 하지만 안타깝게도 이 방식은 원하는 대로 동작하지 않았습니다. 마지막으로 manifest 파일을 이용하여 시도해보았습니다. spec 파일을 이용하여 pyinstaller로 빌드하면 <실행 파일 이름>.manifest 라는 파일이 생성됩니다. 파일에서 아랫부분을 찾아볼 수 있습니다. <security> <re

초간단 프로그램 락 걸기

프로그램에 락을 걸 일이 생겨났다. 하드웨어 락을 걸면 쉬울텐데 그 정도는 아니고 프로그램의 실행 날짜를 제한 해 달라고 한다. 그래서 파일(license.lic)을 가지고 락을 걸리고 결정을 했다. 요구 사항은 아래와 같다. 1. license.lic 파일이 없으면 프로그램을 실행 할수 없게 한다. 2. 지정한 날짜를 넘어서는 프로그램을 실행 할수 없게 한다. 3. 사용자가 시스템 날짜를 되돌렸을때 인식하여 프로그램을 실행 할수 없게 한다. 음.... 1.번 문제는 사용자가 프로그램을 실행하기 위해서 license.lic 파일을 받아야만 한다. license.lic 파일에는 최근 실행 날짜/종료날짜 이런식으로 적도록 한다.(물론 내용은 암호화 한다.) 최근 실행날짜는 프로그램이 실행때마다 업데이트 하도록 하고 시스템 날짜와 비교하여 시스템 날짜가 최근 실행 날짜보다 이전의 날짜면 시스템 날짜를 되돌렸다고 인식하도록 한다.(3.번 문제 해결) 시스템 날짜와 종료 날짜를 비교하여 시스템 날짜가 종료 날짜를 넘으면 프로그램을 실행 할수 없도록 한다.(2.번 문제 해결)