簡體   English   中英

MFC-顯示模式對話框時主窗口變暗

[英]MFC - dim main window when showing modal dialog

我有一個相當標准的MFC應用程序,它包含一個主窗口,偶爾會彈出模式對話框。 眾所周知,在關閉模式對話框之前,無法進行任何其他操作。

因此,一個不錯的UI功能是“隱藏”對話框后面的主窗口的其余部分,以直觀地指示您直到完成模態對話框后才能使用它。 一些Web應用程序和Java / Mac應用程序可以做到這一點,但是我從未見過在傳統的C ++ / MFC應用程序中做到這一點。 即使平台不常見,我也想嘗試一下。

如何才能做到這一點? 我在應用程序中有幾種模式對話框,用於此模式:

// pMainFrame is available as a pointer to the CWnd of the main window
CMyDialog dialog;
dialog.DoModal(); // invoke modal dialog; returns after dialog closed

有沒有一種簡單的方法可以使窗口在任何DoModal()之前變暗並在之后恢復? 我正在使用Visual Studio 2010,以防更新的MFC具有任何可能有用的功能。

編輯:我已經發布了一個基於oystein答案的解決方案,但是如果有人可以改進它,我將開始提供賞金-尤其是平滑的淡入/淡出效果。

您可以在要調暗的窗口之上創建另一個全黑窗口,並使用SetLayeredWindowAttributes設置黑窗口的不透明度。 當然,它不一定必須是黑色的,但是我想那是最好的調光顏色。

編輯:我砍了一個例子-但請注意,我不是MFC開發人員,我通常直接使用Windows API。 不過,它似乎工作正常。 是一個pastebin。 隨時自己添加淡入等。 另請注意,這會使整個屏幕變暗,如果您不希望這種行為,則必須調整我的變暗窗口的大小。 查看代碼注釋。

/**********************************************************************************************

    MFC screen dim test
        :: oystein          :: November 2010

    Creates a simple window - click it to toggle whether a translucent black "dimmer" window 
    is shown. The dimmer-window covers the entire screen, but the taskbar ("superbar" in 
    Windows 7) will jump on top of it if clicked - it seems. Simple suggestions to fix that
    are welcome.

    Should work on Windows 2000 and later. 

    Disclaimer: This is my first MFC program ever, so if anything seems wrong, it probably is.
    I have previously only coded with pure Win32 API, and hacked this together using online
    tutorials. Code provided "as-is" with no guarantees - I can not be held responsible for 
    anything bad that happens if you run this program.

***********************************************************************************************/

#include "stdafx.h"

#undef WINVER
#define WINVER 0x500 // Windows 2000 & above, because of layered windows


// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
//                       Black window used to dim everything else 
//
class CDimWnd : public CFrameWnd
{               
public: 
    CDimWnd()
    {
        // Get screen res into rect
        RECT rc;
        GetDesktopWindow()->GetWindowRect(&rc);

        CreateEx(WS_EX_LAYERED |        // Layered window for translucency
                 WS_EX_TRANSPARENT |    // Click through
                 WS_EX_TOPMOST |        // Always on top
                 WS_EX_TOOLWINDOW,      // Do not appear in taskbar & similar
                 NULL, TEXT(""), 
                 WS_POPUP,              // No frame/borders - though there is 
                                        // still some border left - we'll remove 
                                        // it with regions

                 0, 0, rc.right + 10, rc.bottom + 10, // Make the window 10px larger 
                                                      // than screen resolution in both 
                                                      // directions - it is still positioned 
                                                      // at 0,0
                 NULL, NULL);

        // Grab a part of the window the size of the desktop - but 5px into it  
        // Because the window is larger than the desktop res, the borders are removed 
        CRgn rgn;                         
        rgn.CreateRectRgn(rc.left + 5, rc.top + 5, rc.right + 5, rc.bottom + 5);
        SetWindowRgn((HRGN)rgn, FALSE);
        rgn.Detach();                               

        // We have to reposition window - (0,0) of window has not changed
        SetWindowPos(NULL, -5, -5, 0, 0, SWP_NOSIZE | SWP_NOZORDER);        

        // This is where we set the opacity of the window: 0-255
        SetLayeredWindowAttributes(RGB(0,0,0), 150, LWA_ALPHA);                     
    }
    void Close()
    {
        CFrameWnd::OnClose();
    }
    BOOL CDimWnd::OnEraseBkgnd(CDC* pDC); // Set BKG color
    DECLARE_MESSAGE_MAP()
};

BOOL CDimWnd::OnEraseBkgnd(CDC* pDC)
{
    // Set brush to desired background color
    CBrush backBrush(RGB(0, 0, 0));

    // Save old brush
    CBrush* pOldBrush = pDC->SelectObject(&backBrush);

    CRect rect;
    pDC->GetClipBox(&rect);     // Erase the area needed

    pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATCOPY);
    pDC->SelectObject(pOldBrush);   
    return TRUE;
}

BEGIN_MESSAGE_MAP(CDimWnd, CFrameWnd)
    ON_WM_ERASEBKGND()
END_MESSAGE_MAP()

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


// Global variable - is screen dimmed?
bool g_bIsDimmed = false;


// The main window
class CMainWnd : public CFrameWnd
{     
    // Contains a CDimWnd - I'm not sure if this is the "MFC way" of doing things
    CDimWnd dimmer; 

public: 
    CMainWnd()
    {
        Create(NULL, TEXT("Screen dimmer - Press left mouse button on window to toggle"), 
            WS_OVERLAPPEDWINDOW, CRect(50, 50, 400, 250));
    }
    // Left mouse button toggles dimming
    afx_msg void OnLButtonDown(UINT Flags, CPoint Point)
    {
        if(!g_bIsDimmed)
        {
            dimmer.ShowWindow(SW_SHOW);
            dimmer.BringWindowToTop();          
            g_bIsDimmed = true;
        }
        else
        {           
            dimmer.ShowWindow(SW_HIDE);     
            g_bIsDimmed = false;
        }
    }
    DECLARE_MESSAGE_MAP()
};

BEGIN_MESSAGE_MAP(CMainWnd, CFrameWnd)
    ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()


// The app
class CApp : public CWinApp
{
public:         
    virtual BOOL InitInstance();
};

BOOL CApp::InitInstance()
{               
    m_pMainWnd = new CMainWnd();              
    m_pMainWnd->ShowWindow(m_nCmdShow);           
    m_pMainWnd->UpdateWindow();        
    return TRUE;
}

CApp HelloApp;

更新:

我為您整理了一些其他代碼,以處理衰落。 我仍然不是MFC開發人員,我將代碼保持在“粗糙”狀態(錯誤處理很少,不是很可靠),您也可以做一些事情。 :)無論如何,這是一種方法,我認為它很干凈:

要使用它,請使您的主窗口包含一個調光器窗口

class CMainFrm : public CFrameWnd
{     
    CDimWnd* dimmer; 

public: 
    CMainFrm()
    {
        // constructor code here ...
        dimmer = new CDimWnd();         
    }

// rest of class ...

};  

然后可以像這樣使用它:

dimmer->Show();
MessageBox(TEXT("Hello world"));
dimmer->Hide();

另外,我想如果您想將代碼( Show() / Hide()調用)保留在模態對話框的構造函數和析構函數中,則可以將它們放在其中。 如果您想要“作用域” -dim(如在您發布的示例中一樣),則此代碼必須放入CDimWnd類的構造函數和析構函數中,並且您將需要諸如靜態成員變量之類的內容以確保僅一個調光器一次運行(除非您要使用全局變量)。

對於調光器窗口-我這樣做:

CDimWnd.h

#define TARGET_OPACITY 70   // Target opacity 0-255 for dimmed window
#define FADE_TIME 20        // Time between each fade step in milliseconds
#define FADE_STEP 5      // How much to add to/remove from opacity each fade step
#define ID_FADE_TIMER 1

// Call Show() and Hide() to fade in/fade out dimmer. 
// Creates the dimmer window in constructor.
class CDimWnd : public CFrameWnd
{         
    bool m_isDimming;       

public: 
    CDimWnd();
    void Show();
    void Hide();            

protected:
    BOOL OnEraseBkgnd(CDC* pDC);
    void OnTimer(UINT_PTR nIDEvent);
    DECLARE_MESSAGE_MAP()
};

CDimWnd.cpp

#include "stdafx.h"
#include "CDimWnd.h"
#include "MainFrm.h"

BEGIN_MESSAGE_MAP(CDimWnd, CFrameWnd)
    ON_WM_ERASEBKGND()
END_MESSAGE_MAP()

CDimWnd::CDimWnd()
{
    // Get the main frame of the application which we want to dim.
    CMainFrame* pParent = theApp.pMainFrame;

    // Don't do anything if the main frame doesn't appear to be there
    if (pParent != NULL)
    {
        // Get the client area of the window to dim.
        CRect rc;
        pParent->GetClientRect(&rc);
        pParent->ClientToScreen(&rc);       // convert to screen coordinates

        // Do some fudging to fit the client area exactly.
        // Other applications may not need this if the above client area fits already.
        rc.top += GetSystemMetrics(SM_CYFRAME);
        rc.top += GetSystemMetrics(SM_CYCAPTION);           // MFC feature pack seems to include caption in client area
        rc.left -= GetSystemMetrics(SM_CXBORDER);
        rc.right += GetSystemMetrics(SM_CXBORDER) + 1;
        rc.bottom += GetSystemMetrics(SM_CYBORDER) + 1;

        // Create a layered window for transparency, with no caption/border.
        CreateEx(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW, NULL, TEXT(""), 
            WS_POPUP, rc.left, rc.top, rc.Width(), rc.Height(),
            pParent->GetSafeHwnd(), NULL);
    }
}


void CDimWnd::Show()
{
    // If we are not already dimming, go for it
    if(!m_isDimming)
    {
        // Bring in front of main window.
        BringWindowToTop();

        // Set opacity to 0
        SetLayeredWindowAttributes(RGB(0,0,0), 0, LWA_ALPHA);

        // Show the dimmer window
        ShowWindow(SW_SHOW);

        // Create timer - the rest is handled in OnTimer() function
        SetTimer(ID_FADE_TIMER, FADE_TIME, NULL);
    }
}


void CDimWnd::Hide()
{   
    // If we are dimming, go for it
    if(m_isDimming)
    {
        // Create timer - the rest is handled in OnTimer() function
        SetTimer(ID_FADE_TIMER, FADE_TIME, NULL);
    }
}


void CDimWnd::OnTimer(UINT_PTR nIDEvent)
{
    static int fade = 0;

    if(nIDEvent == ID_FADE_TIMER)
    {
        // We are dimming => we want to fade out
        if(m_isDimming)
        {
            if(fade < 0)
            {
                // Fading finished - hide window completely, update status & destroy timer
                fade = 0;
                ShowWindow(SW_HIDE);
                KillTimer(nIDEvent);
                m_isDimming = false;
            }
            else
            {
                // Set window opacity & update fade counter
                SetLayeredWindowAttributes(RGB(0,0,0), fade, LWA_ALPHA);
                fade -= FADE_STEP;
            }
        }
        else
        // fade in
        {
            if(fade > TARGET_OPACITY)
            {   
                // Fading finished - destroy timer & update status

                fade = TARGET_OPACITY; // but first, let's be accurate.
                SetLayeredWindowAttributes(RGB(0,0,0), fade, LWA_ALPHA);

                KillTimer(nIDEvent);
                m_isDimming = true;             
            }   
            else
            {
                // Set window opacity & update fade counter
                SetLayeredWindowAttributes(RGB(0,0,0), fade, LWA_ALPHA);
                fade += FADE_STEP;
            }
        }
    }
}


BOOL CDimWnd::OnEraseBkgnd(CDC* pDC)
{
    // Fill with black
    CBrush backBrush(RGB(0, 0, 0));
    CBrush* pOldBrush = pDC->SelectObject(&backBrush);

    CRect rect;
    pDC->GetClipBox(&rect);     // Erase the area needed
    pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATCOPY);

    pDC->SelectObject(pOldBrush);   
    return TRUE;
}

好的。 就像我說的那樣,這是相當快地投入使用的,並且處於粗糙狀態,但是它應該為您提供一些可工作的代碼,以及在MFC中使用(我認為)計時器的一般思路。 我絕對不是合適的人,但是:)

我已經接受了oystein的回答,因為它可以將我引向解決方案,但我認為我應該發表自己的修改。 我必須對其進行一些修改以使其對我有用,因此它可能對其他人很有用。

記錄下來,調光效果很好,但是看起來不像我希望的那樣自然。 在經常打開對話框的應用程序中,調光似乎分散了看似打開和關閉主窗口的規律,從而分散了人們的注意力。 為了妥協,我已經使調光相當微妙(約25%的不透明度),以柔和地突出顯示活動對話框。 即時調光仍然有點讓人分心,但我不確定如何使其淡入或淡出,尤其是在進行范圍調整時。

另外,我不是UI專家,但調光給我一種印象,即該對話框與其背后的窗口內容不太相關。 即使對話框直接操作該內容,這也使我感覺與我在應用程序中所做的工作有些脫節。 這可能是另一個分心的問題。

無論如何,這里:

CDimWnd.h

// Dim the application main window over a scope.  Creates dimmer window in constructor.
class CDimWnd : public CFrameWnd
{               
public: 
    CDimWnd();
    BOOL OnEraseBkgnd(CDC* pDC);

    ~CDimWnd();

protected:
    DECLARE_MESSAGE_MAP()
};

CDimWnd.cpp

#include "stdafx.h"
#include "CDimWnd.h"
#include "MainFrm.h"

BEGIN_MESSAGE_MAP(CDimWnd, CFrameWnd)
    ON_WM_ERASEBKGND()
END_MESSAGE_MAP()

// For preventing two dimmer windows ever appearing
bool is_dimmer_active = false;

CDimWnd::CDimWnd()
{
    // Get the main frame of the application which we want to dim.
    CMainFrame* pParent = theApp.pMainFrame;

    // Don't do anything if the main frame doesn't appear to be there,
    // or if there is already dimming happening.
    if (pParent != NULL && !is_dimmer_active)
    {
        // Get the client area of the window to dim.
        CRect rc;
        pParent->GetClientRect(&rc);
        pParent->ClientToScreen(&rc);       // convert to screen coordinates

        // Do some fudging to fit the client area exactly.
        // Other applications may not need this if the above client area fits already.
        rc.top += GetSystemMetrics(SM_CYFRAME);
        rc.top += GetSystemMetrics(SM_CYCAPTION);           // MFC feature pack seems to include caption in client area
        rc.left -= GetSystemMetrics(SM_CXBORDER);
        rc.right += GetSystemMetrics(SM_CXBORDER) + 1;
        rc.bottom += GetSystemMetrics(SM_CYBORDER) + 1;

        // Create a layered window for transparency, with no caption/border.
        CreateEx(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW, NULL, TEXT(""), 
            WS_POPUP, rc.left, rc.top, rc.Width(), rc.Height(),
            pParent->GetSafeHwnd(), NULL);

        // Bring in front of main window.
        BringWindowToTop();

        // Apply 25% opacity
        SetLayeredWindowAttributes(RGB(0,0,0), 64, LWA_ALPHA);

        // Show the dimmer window
        ShowWindow(SW_SHOW);

        is_dimmer_active = true;
    }
}

CDimWnd::~CDimWnd()
{
    is_dimmer_active = false;
}

BOOL CDimWnd::OnEraseBkgnd(CDC* pDC)
{
    // Fill with black
    CBrush backBrush(RGB(0, 0, 0));
    CBrush* pOldBrush = pDC->SelectObject(&backBrush);

    CRect rect;
    pDC->GetClipBox(&rect);     // Erase the area needed
    pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATCOPY);

    pDC->SelectObject(pOldBrush);   
    return TRUE;
}

用法非常簡單:因為CDimWnd在其構造函數中創建自己,所以您要做的就是將CDimWnd dimmer添加為對話框類的成員,並且無論您從何處調用對話框,它都會自動使主窗口變暗。

您還可以在范圍內使用它來使系統模式對話框變暗:

{
    CDimWnd dimmer;
    MessageBox(...);
}

我無法抗拒這樣做。

它是添加了計時器並實現淡入/淡出的代碼。 我也改變了使用中間灰色而不是黑色的遮擋塊。

您可以通過增加持續時間或增加速率來調整控制淡入淡出的常數以使其更平滑。 實驗表明10hz的速率對我來說是平滑的,但是YMMV

// DimWnd.h : header file
#pragma once

class CDimWnd : public CFrameWnd
{
public:
    CDimWnd(class CWnd * pParent);
    virtual ~CDimWnd();
    BOOL OnEraseBkgnd(CDC* pDC);
    int opacity, opacity_increment;
protected:
    DECLARE_MESSAGE_MAP()

public:
    afx_msg void OnTimer(UINT_PTR nIDEvent);
    void fadeOut();
};

// DimWnd.cpp : implementation file
//

#include "stdafx.h"
#include "dimmer.h"
#include "DimWnd.h"
#include "MainFrm.h"
#include <math.h>

const int TIMER_ID = 111;

// For preventing two dimmer windows ever appearing
bool is_dimmer_active = false;

// constants to control the fade.
int    ticks_per_second  = 1000; // ms
int    start_opacity     = 44;   // 20%
int    max_opacity       = 220;  // 0->255
double fade_in_duration  = 4;    // seconds to fade in  (appear)
double fade_out_duration = 0.2;    // seconds to fade out (disappear)
int    rate              = 100;  // Timer rate (ms


CDimWnd::CDimWnd(CWnd * pParent)
{
    // Don't do anything if the main frame doesn't appear to be there,
    // or if there is already dimming happening.
    if (pParent != NULL && !is_dimmer_active)
    {
        // Get the client area of the window to dim.
        CRect rc;
        pParent->GetClientRect(&rc);
        pParent->ClientToScreen(&rc);       // convert to screen coordinates

        // Do some fudging to fit the client area exactly.
        // Other applications may not need this if the above client area fits already.
        rc.top += GetSystemMetrics(SM_CYFRAME);
        rc.top += GetSystemMetrics(SM_CYCAPTION);           // MFC feature pack seems to include caption in client area
        rc.left -= GetSystemMetrics(SM_CXBORDER);
        rc.right += GetSystemMetrics(SM_CXBORDER) + 1;
        rc.bottom += GetSystemMetrics(SM_CYBORDER) + 1;

        // Create a layered window for transparency, with no caption/border.
        CreateEx(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW, NULL, TEXT(""), 
            WS_POPUP, rc.left, rc.top, rc.Width(), rc.Height(),
            pParent->GetSafeHwnd(), NULL);

        // Bring in front of main window.
        BringWindowToTop();

        // Show the dimmer window
        ShowWindow(SW_SHOW);


        double increment_per_second = ((max_opacity - start_opacity) / fade_in_duration);
        opacity_increment = ceil(  increment_per_second / (ticks_per_second / rate) ) ;

        is_dimmer_active = true;
        opacity = start_opacity;

        SetLayeredWindowAttributes(RGB(0,0,0), opacity, LWA_ALPHA);

        SetTimer(TIMER_ID, rate,NULL);  

    }
}

CDimWnd::~CDimWnd()
{
    fadeOut(); // fade the window out rather than just disappearing.
    is_dimmer_active = false;
}

void CDimWnd::fadeOut()
{
    // can't use timers as may be in the process of being destroyed so make it quick..

    double increment_per_second = ((opacity - start_opacity) / fade_out_duration);
    opacity_increment = ceil(  increment_per_second / (ticks_per_second / rate) ) ;

    while(opacity  > start_opacity)
    {
        opacity -= opacity_increment;
        SetLayeredWindowAttributes(RGB(0,0,0), opacity, LWA_ALPHA);
        Sleep(100);
    }
}

BOOL CDimWnd::OnEraseBkgnd(CDC* pDC)
{
    // Fill with midgray
    CBrush backBrush(RGB(128,128,128));
    CBrush* pOldBrush = pDC->SelectObject(&backBrush);

    CRect rect;
    pDC->GetClipBox(&rect);     // Erase the area needed
    pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATCOPY);

    pDC->SelectObject(pOldBrush);   
    return TRUE;
}

BEGIN_MESSAGE_MAP(CDimWnd, CFrameWnd)
    ON_WM_ERASEBKGND()
    ON_WM_TIMER()
END_MESSAGE_MAP()

void CDimWnd::OnTimer(UINT_PTR nIDEvent)
{
    if (opacity >= max_opacity) 
    {
        // stop the timer when fade in finished.
        KillTimer(TIMER_ID);
        return;
    }

    opacity += opacity_increment;
    SetLayeredWindowAttributes(RGB(0,0,0), opacity, LWA_ALPHA);

    CFrameWnd::OnTimer(nIDEvent);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM