Click here to Skip to main content
Click here to Skip to main content

Go to sleep! Fade to B/W

By , 9 Nov 2003
 

Introduction

Did you ever notice that when you shutdown Windows/XP there is a fading effect from color to B/W on the desktop? Ok that's the objective of this article, a simple way to capture a given window and fade it in an inactive status.

The main idea to perform this operation is quite simple: the code basically creates a fading-window over the target one. This fading-window has all the needing to make this simple animation and the complete implementation is not long and it's based on 3 parts:

  • a snap-shot routine to copy the given window in an in-memory bitmap,
  • a function to decolorize the given bitmap,
  • the main loop to step the decolorizing.

Notice: this code will work only on 16, 24 or 32 bit display color mode.

Using the code

There are basically 2 modalities to perform the fading process: automatic and controlled.

Automatic - this is the simplest way, and it can be used to put the given window in a "relaxed" mode - when the user will click on the given window, this will return to it's original status - here the simple steps to start with this operation:

  1. add the FadeWnd.h and FadeWnd.cpp, to your project,
  2. include the FadeWnd.h in the implementation code (.cpp) where you will call the fading effect,
  3. simply call the CFadeWnd::AutoFade(CWnd* pWnd) on the window you want to fade.

Controlled - don't worry, this is quite easy too, the difference is that we want to control the moment the fading effect must finish. For this, I have assumed that the fading operation must simply be done before a modal window call - here the steps:

  1. as before, add the FadeWnd.h and FadeWnd.cpp, to your project,
  2. include the FadeWnd.h in the implementation code (.cpp) where you will call the fading effect,
  3. define a CFadeWnd object before a dialog or a message-box modal call, for sample: wndFade,
  4. create the fade window, passing as parent the window to fade as shown: wndFade.Create(this).

Difficult?

Let's code!

Remember, first at all, add the FadeWnd.h and FadeWnd.cpp, to your project. To do this, copy these 2 files in the folder of your project, and from the [Project] menu item of the Visual Studio, choose [Add to Project] -> [Files] voice. Select the 2.

Next step, include the FadeWnd.h in the implementation code (.cpp) where you will call the fading effect. If you want to use the CFadeWnd class a bit every where, you can include it in the stdafx.h.

#include "FadeWnd.h"

To use it in a simple way, you can perform the call:

void CMakeInactiveDlg::OnButton1() 
{
    CFadeWnd::AutoFade(this);
}

Fade all the desktop:

void CMakeInactiveDlg::OnButton2() 
{
    CFadeWnd::AutoFade(GetDesktopWindow());
}

Fade the given window for the necessary modal sub-window call:

void CMakeInactiveDlg::OnButton3() 
{
    CFadeWnd wndFade(this);
 
    // modal window call as a DIALOG or a MESSAGEBOX
    AfxMessageBox(
        _T("Disabled until this message will be closed"),
        MB_OK | MB_ICONINFORMATION);
}

Fade using a different gradient color:

void CMakeInactiveDlg::OnButton4() 
{
    CFadeWnd::AutoFade(
        this,                // window to fade
        RGB(255,128, 64),    // light color ref
        RGB( 64, 16,  0));   // dark color ref
}
 
// - or -
 
void CMakeInactiveDlg::OnButton5() 
{
    CFadeWnd wndFade(
        this,                // window to fade
        RGB(255,128, 64),    // light color ref
        RGB( 64, 16,  0));   // dark color ref
 
    // modal window call as a DIALOG or a MESSAGEBOX
    AfxMessageBox(
        _T("Disabled until this message will be closed"),
        MB_OK | MB_ICONINFORMATION);
}

Notices

To permit other programmers to change the behavior of this control, I have added 3 virtual members that can be easily overridden:

  • void CreateGradient(...) - this allow to try other fading algorithms
  • bool OnLButtonCheck() - this is needed to make security checks directly inside the CFadeWnd during left button mouse clicks
  • bool OnRButtonCheck() - same as above, but for right button mouse clicks

Play with the CreateGradient call

I have made virtual the CreateGradien member of the CFadeWnd. This will allow some programmers to play with this call deriving a new class from the CFadeWnd. Let's see a sample of this process.

Create your derived class, for sample:

class CMyGradientFadeWnd : public CFadeWnd
{
public:
    virtual void CreateGradient(
        COLORREF /* clrLight = RGB(255,255,255) */,  // parameters are not 
                                                     // used in this sample
        COLORREF /* clrDark  = RGB(  0,  0,  0) */)
    {
        for(int i=0; i<256; i++)
        {
            m_clrGradient[i] = RGB(i, 255-i, i);
        }
    }
};

Now you have only to use your CMyGradiendFadeWnd in substitution of the CFadeWnd in your application.

Intercepting the left and right mouse button clicks inside the CFadeWnd class using OnLButtonCheck and OnRButtonCheck calls

Of course, this could be done deriving the whole class with CLASSWIZARD, and for more skilled developers, I'll suggest to do it that way - but to allow fast and easy way to inject our own made dialogs directly in the CFadeWnd, I have made the 2 overridden calls.

As for the CreateGradiend saw before, create your derived class, for sample:

class CMyPasswordFadeWnd : public CFadeWnd
{
public:
    virtual bool OnLButtonCheck()
    {
        // add the password check here
        CPasswordDlg dlg; // make your own dialog
        return (dlg.DoModal() == IDOK);
    }
    virtual bool OnRButtonCheck() { return false; } // no response
};

Credits - Special thanks to

Credits are reported inside the source code. The major help come from these articles/posts:

History

  • 10 November 2003 - bug fixes and some new things from the message posts:
    • virtual CreateGradient(...) call to perform a different graying effect
    • virtual OnLButtonChek() and OnRButtonChek() to perform a mouse click security check inside the CFadeWnd class
    • timing calculation to make the fading effect fit in less than 2 seconds
    • region heredity for shaped windows (example skinned windows)
    • disabled the parent window during the fade process, and eliminated the icon on the task-bar
  • 3 November 2003 - first public release

// Todo :

  • ... and the list is growing

Of course, all suggestions are welcome

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

John A. Johnson
Chief Technology Officer http://www.johnson.vi.it
Italy Italy
Member
Details count.
 
Has gained his experience working in the management with several private companies, both production and services kind of farms, especially in managerial, technical direction, as a trainer and marketing / sales, as well as considerable experience in project management.
 
Has completed his technical / scientific expertise with several companies and universities working on software engineering, industrial automation and production at various levels, producing CAD for textiles (in the press and yarn, both for design applications and treatment of color and digital printing), incorporation of the farm, factory automation (with significant experience on textiles, plastics, luxury mechanics and dyes) to complete the design of ERP systems (fiscal, analytical, warehouse, quality systems, quality control, production scheduling to finite and infinite capacity).
 
Facebook: http://www.facebook.com/john.andrew.johnson
Linkedin: http://www.linkedin.com/in/johnajohnson

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionUpdated for VB.Net or C#?memberTim8w19 Jun '08 - 12:47 
Have you or anyone updated this for .Net?
 
Tim Alvord

AnswerRe: Updated for VB.Net or C#?memberJohn A. Johnson23 Jun '08 - 21:22 
I never really worked in C#, so I'm not able to help directly.
 
I think that the correct process will be to make a DLL from this code to integrate these functions in a .NET project.
 
Andy
 

AnswerRe: Updated for VB.Net or C#?membershenjian7 Feb '10 - 4:44 
I am waiting for one dll for .net!
 
slcands
GeneralRe: Updated for VB.Net or C#?memberyjvujj30 Sep '11 - 8:05 
You can make this project to a Dll .then use "DLLImport" to find function symbol (function pointer) .
 
That's dynamic call between two different lauguage
bbs.whnet.edu.cn(From China )

QuestionGreat code but how can I do this?sussAnonymous5 Oct '04 - 11:50 
Hi! Thanks for the great code. I can make it work from my dialog app and fade my main window when I call other dialogs modal but if I call a COM object which displays a dialog the COM object dialog is not set to the foreground and I cannot select it and I must close it from the taskbar. This only happens if I call WndFade. Am I doing something wrong? Is it that calling a modal dialog is still part of my program execution but the COM object is not? Would this also cause a problem if I called any other external program?
QuestionIs there a Way to set XP generally to B/W ?membere-t-c26 Sep '04 - 23:01 
Hi,
I'm not a Programmer,
and i'm registred today only for Your Tool Roll eyes | :rolleyes:
 
My Question:
Is there a Way (or Tool),
to set the Color in XP generally to Black & White (Grey)?
 
Thank You Blush | :O )
e-t-c
GeneralLeaving a windowsussAnonymous20 Jun '04 - 4:29 
I want to call this when I leave my window as if I had clicked on another window.
 
I overloaded OnActivate() in my dialog class and tested nState for WA_INACTIVE but it does not work. Have you any ideas what I can do as I think this would be useful interface function as it looks very nice Smile | :)
GeneralC#memberHarsmaken18 May '04 - 8:20 
Can't you create a DLL out of your code so I can call it from C#, I tried to convert, but I don't know how to program in C++.
GeneralPreventing a WM_CLOSE message for CFadeWnd (e.g. Alt+F4) + fixmemberValentin Mocanu18 Mar '04 - 2:27 
I found a small problem using your code. Fade window could be closed by pressing Alt+F4.
The quick fix (among many) for this should be:
 
void CFadeWnd::OnClose()
{
//CWnd::OnClose();
return;
}

 
And of course we have to deal with WM_QUERYENDSESSION, WM_ENDSESSION if this code is used to lock the application.
 
Rose | [Rose] Thanks a lot for your good work!

GeneralCoolmemberHockey14 Feb '04 - 13:33 
I have an application where the main window is a system modal dialog and it's entire display is a bitmap, I would like the Fader control to fade out (greyed) when the window is no longer active.
 
I have tried handling OnActivate and fading the window in here when appropriate, but the window never fades, except when I click on the task bar or desktop, not an application that lays underneath???
 
Also when it faded, i couldn't get the fade to go away???
 
Any ideas???
 
Thanks for the cool code
 
Cheers Smile | :)
 
The word of the day is legs, let's go back to my house and spread the word Poke tongue | ;-P
QuestionFading non-rectangular dialogs?membert00lb0x_t00lb0x25 Jan '04 - 4:01 
I've been playing with the code, trying to fade a non-rectangular dialog window using regions. I managed to fade the window when it lost focus, then noticed that the window and entire bounding rectangle were being faded.
 
Any ideas? D'Oh! | :doh:
 
BTW, kudos to the author of this fine code!
AnswerRe: Fading non-rectangular dialogs?memberA sleepy one29 Jan '04 - 23:48 
Strange, this must correctly work.
 
But I have notice that the "only source[^]" download haves a different version of the "demo[^]".
 
The "demo" haves the correct fading code. For sure this must be mine mistake during one past article update.
 
Cool | :cool:
 
John A. Johnson
GeneralSmall bug and fixmemberAndrew122 Dec '03 - 2:03 

Nice work!!!
Smile | :)
 
But there is small bug
 
Drag window to set its left or top side(s) off screen and now do fade
and we get bitmap in the wrong place.
 
FIX ------------------------>
 
BOOL CFadeWnd::Create(CWnd* pParentWnd, bool bAutoDel, CRect rc)
{
................................................
if (rc == CRect(0,0,0,0))
pParentWnd->GetWindowRect(rc);
 
//<-------------------------------------------
// FIX Add this
if(0 > rc.left)
{
rc.right -= rc.left;
rc.left = 0;
}
 
if(0 > rc.top)
{
rc.bottom -= rc.top;
rc.top = 0;
}
//--------------------------------------------
 

 

QuestionFading like in WinXP?memberMirza Miletic18 Dec '03 - 11:04 
Is it possible to fade desktop, but my app window to stay in color? Confused | :confused: Confused | :confused: Confused | :confused:
AnswerRe: Fading like in WinXP?memberA sleepy one29 Jan '04 - 23:43 
I was not able to post updates lately, hope I can solve this soon.
 
Anyway, what you are asking needs a MILTI-THREAD implementation of the class.
 
This will allow you to fade the "back" window while the "on top" is active.
 
take a look to this thread http://www.codeproject.com/dialog/WinMakeInactive.asp?msg=670062#xx670062xx[^]
 
Cool | :cool:
 
John A. Johnson
GeneralKeep updatingmemberMajor Major20 Nov '03 - 1:48 
First of all, I must agree with all the rest - a very nice idea and article!
 
The thing I would like is to keep the background being updated. For example, when there is a progress bar in the fading dialog, it should keep updating. Any ideas how to do this?
 
Major
GeneralRe: Keep updatingmemberJohn A. Johnson20 Nov '03 - 22:49 
Thank you very much.
 
I have made a try to perform your request.
 
What came out was an interesting effect, but not the hoped behavior.
 
Probably I'll have to rewrite the "CopyScreenToBitmap" because it catches the "topmost" graphics data. For your request, I have to catch the parent window of the CFadeWnd class.
 
I cant promise this for my next update, but for sure I'll work on it.
 
Cool | :cool:

GeneralRe: Keep updatingmemberMajor Major24 Nov '03 - 2:36 
Waiting with anticipation Laugh | :laugh:
GeneralThats GreatmemberBalkrishna Talele19 Nov '03 - 20:07 
That’s outstanding stuff I have had experienced, It really catchy.
GeneralWow!membermachocr13 Nov '03 - 6:29 
It is great, good job.Eek! | :eek:
I ve erver want somthing like this. I try it some similar with transparent efects but is has many problems for the user.
Can us will see it in CSharp in future? Roll eyes | :rolleyes:
 
La realidad no es más que impulsos eléctricos del cerebro - Morpheus
GeneralRe: Wow!memberJohn A. Johnson16 Nov '03 - 23:14 
If it's aceptable for you to add a DLL to your C# project, then I think that there is a solution to use this class in a VB/C# project.
 
What I can do, is a DLL version of the project, with an exported function call to fade the interested window by handle.
 
What you must do by your part is to import the DLL and make the call giving to the exported function call, the handle of the window you want to fade.
 
I have already saw this solution some other part, but honestly, I'm not practice of C#. What I need is help from someone to test the DLL.
 
Cool | :cool:
GeneralGreat code! one minor thing..memberBoonchai M.12 Nov '03 - 20:20 
Sometimes, when return from fading, if parent dialog has other windows behind it, it probably will give the focus to one of other windows so it will look like the dialog disapear once before showing back.
you can fix by take the code from ~CFadeWnd()

m_pWndLock->EnableWindow();
m_pWndLock->SetFocus();

and put it before every call of

DestroyWindow();

giving the focus back to the parent before destroy the fading dialog.;)
GeneralRe: Great code! one minor thing..memberJohn A. Johnson12 Nov '03 - 20:30 
Thank you for your tip - I was not able to repeat your problem.
 
The DestroyWindow call will be reviewd because soon I'll update the code with a separated fading process thread - Jeremy Davis is helping me in this.
 
For sure, I'll follow your sequence suggestion:
 
-> Enable
-> SetFocus
-> Destroy
 
Cool | :cool:

QuestionHow about doing the fade in a thread?memberJeremy Davis12 Nov '03 - 0:32 
Great class by the way!
 
I use this in my app to fade the background when the Exit button is pressed, and I bring up an "Are You Sure?" messagebox. The thing is, the 1 - 2 seconds it takes to fade before my messagebox appears will annoy users that just want to exit quickly. It would be good if the background could slowly fade, whilst the messagebox is displayed.
 
Perhaps put it in a thread? I dunno. I'll have a go, but please do bear in mind I design hardware, with a small amount of software, so it may be bug ridden. Blush | :O
 


I feel like I'm diagonally parked in a parallel universe
 
Jeremy Davis
http://www.astad.org
http://www.jvf.co.uk
AnswerRe: How about doing the fade in a thread?memberJohn A. Johnson12 Nov '03 - 1:07 
Hi Jeremy,
 
I have another request to put the main fading loop in a separated thread - I didn't do anything yet - so if you have already work a bit in this direction... it's wellcome. Big Grin | :-D
 
Only attention to this point, the feature must match with a FadeBack option that it's not done too (only a small tip on a previous post). Roll eyes | :rolleyes:
 
Thank you very much,
 
Cool | :cool:
GeneralRe: How about doing the fade in a thread?memberskratt19 Nov '03 - 5:40 
First off, I must say this is a great class that you have created.....
Smile | :)
Now the thread:
 
Here you go.
 
Add to the class definition: (FadeWnd.h)
protected:
   static UINT FadeThread(LPVOID pParam);
Change the Create handler to begin the thread, not do the loop: (FadeWnd.cpp)
BOOL CFadeWnd::Create(CWnd* pParentWnd, bool bAutoDel, CRect rc) 
{
   .
   .
   .
   .
 
   // drawing loop (directly in the creation look);
   m_bAutoDel   = bAutoDel;
   m_hBitmap    = CopyScreenToBitmap(rc);
 
// Added >
   AfxBeginThread(FadeThread,  static_cast<LPVOID>(this));
// Added <
   
   return TRUE;
}
 
Add to the implementation: (FadeWnd.cpp)
 
UINT CFadeWnd::FadeThread(LPVOID pParam)
{
   CFadeWnd * pWnd = static_cast<CFadeWnd *>(pParam);
 
   CClientDC dc(pWnd);
   int nStep = 0;
   for (int i=0; i<100; i+=nStep)
   {
      DWORD dwStartCount = timeGetTime();	// tick counter in milliseconds

      if(pWnd->m_hNewBitmap)
      {
         DeleteObject(pWnd->m_hNewBitmap);
         pWnd->m_hNewBitmap = NULL;
      }
 
      pWnd->m_hNewBitmap = pWnd->FadeBitmap(pWnd->m_hBitmap,(double)i);
 
      pWnd->OnDraw(&dc);
 
      DWORD dwEndCount = timeGetTime();	// tick counter in milliseconds

      if (nStep == 0)
      {
         // timer frequency calculation
         if (dwEndCount > dwStartCount)
            nStep = 1500 / (dwEndCount - dwStartCount);  // close in 1.5 sec
         else
            nStep = 20;
 
         // time to frequency
         nStep = 100 / nStep;
 
         nStep = max(nStep,  3);	// min allowed
         nStep = min(nStep, 49);	// max allowed

         TRACE("Loop frequency: %d\n", nStep);
      }
   }
 
   return 0;
}
The FadeBack part is similar, Just create a FadeBackThread and call the begin thread from within the FadeBack method.
 
Hope this helps, it sure helped me.
 
Cool | :cool:

GeneralRe: How about doing the fade in a thread?memberJohn A. Johnson19 Nov '03 - 9:03 
Thank you Skratt,
 
I have already implemented this point, a bit different but based on the same principle that I'll post soon - but honestly I don't know when. So your post is wellcome for all the people that need this feature and can't wait my update - thank you very much.
 
Only one point. Playing with threads, because the window can destroy itself before the fading is ended, there are some things to pay attention...
 
When you create the process, store the thread process:
 
	m_pThread = AfxBeginThread(FadeThread, static_cast(this));
 
in the destructor, to be sure that the process is "dead", something like:
 
	...
	if (m_pThread)
	{
	//	CWaitCursor cur;

		m_bStopTh = TRUE;    // this is a stopping flag
		while(m_bStopTh)     // must be set to FALSE at the end of
			::Sleep(0);  // thread function

		HANDLE hThread = m_pThread->m_hThread;
		if (::WaitForSingleObject(hThread, 64000) == WAIT_TIMEOUT)
			::TerminateThread(hThread, (UINT)-2);
	}
 
Thank you again
 
Cool | :cool:

GeneralWile E CoyotememberPaul Evans11 Nov '03 - 22:35 
The article looks good, and the Coyote rocks! Now I know who else may be registring things like wile_e as logins Wink | ;-)
 
Anyway it got my 5, and any messages with decent wile e coyote links on it will probably get that too Smile | :)
 
Cheers,
 
Paul
 


GeneralExcellentmembermanos_crete11 Nov '03 - 20:34 
Very impressive Big Grin | :-D
 
Manolis from Crete Smile | :)
GeneralYet another.susslusores11 Nov '03 - 6:17 
Few years ago i was busy with same task. Here is sample function:
 
DWORD* MoveToBnW ( float step /* 0..100 */, BYTE* dst /* ptr to RGB array */) {
int Size = cx * cy;
while ( Size-- ) {
dst[0] = (BYTE)(dst[0] * ( .11 + step * .0089 ) + ( dst[1] * .59 + dst[2] * .30 ) * ( 1 - step * .01 ));
dst[1] = (BYTE)(dst[1] * ( .59 + step * .0041 ) + ( dst[0] * .11 + dst[2] * .30 ) * ( 1 - step * .01 ));
dst[2] = (BYTE)(dst[2] * ( .30 + step * .0070 ) + ( dst[0] * .11 + dst[1] * .59 ) * ( 1 - step * .01 ));
dst+=4;
};
 
// enjoy ;)

 
May be it'll be useful..

 
../ Lusores
GeneralGood Job!memberMrLeeGriffiths10 Nov '03 - 23:51 
Nice job my son - very impressed with its simple ease of use. Keep up the good work. One thing you could also try is alpha blending the window with the background - so as well as fading the colour it also becomes semi transparent (or offer a alpha value to determine its transparency).

GeneralFade it backmemberVerifier10 Nov '03 - 23:37 
Hello
 
I want to fade my app when someone enters a take-a-break mode (templogout).
 
The question is: How do I fade it back to the original colors when the user gets back and log in again?
GeneralRe: Fade it backmemberJohn A. Johnson11 Nov '03 - 2:53 
Right, in my mind there was this option too... but... I forgot to write it... Roll eyes | :rolleyes:
 
you can add the following call to the implementation... in future I'll add it to the article:
 
void CFadeWnd::FadeBack()
{
	if (!IsWindow(GetSafeHwnd())  ||  !m_hBitmap  ||  !m_hNewBitmap)
		return;
 
	CClientDC dc(this);
 
	int nStep = 0;
	for (int i=0; i<100; i+=nStep)
	{
		DWORD dwStartCount = timeGetTime();	// tick counter in milliseconds
 
		if(m_hNewBitmap)
		{
			DeleteObject(m_hNewBitmap);
			m_hNewBitmap = NULL;
		}
 
		m_hNewBitmap = FadeBitmap(
			m_hBitmap,
			100.0 - (double)i);
 
		OnDraw(&dc);
 
		DWORD dwEndCount = timeGetTime();	// tick counter in milliseconds
 
		if (nStep == 0)
		{
			// timer frequency calculation
			if (dwEndCount > dwStartCount)
				nStep = 1500 / (dwEndCount - dwStartCount);  // close in 1.5 sec
			else
				nStep = 20;
 
			// time to frequency
			nStep = 100 / nStep;
 
			nStep = max(nStep,  3);	// min allowed
			nStep = min(nStep, 49);	// max allowed

			TRACE("Loop frequency: %d\n", nStep);
		}
	}
}
 
This function call must be used in what I call the "controlled" way... sample:
 
void CMakeInactiveDlg::OnCall() 
{
	CFadeWnd wndFade(this);
 
	AfxMessageBox(
		_T("Disable until this message will be closed"),
		MB_OK | MB_ICONINFORMATION);
 
	// add the following line
	wndFade.FadeBack();
}
 
Cool | :cool:
GeneralPretty cool...memberbenjaminl10 Nov '03 - 7:44 
Interesting effect... I find myself wondering where I could use it in my current project because I like it so much. Smile | :) Perhaps a time delayed automatic user logoff.
 
I've got one that you might not have tested for yet:
I tried to run the release on my dual monitor system in which the desktop spans across both monitors. I found that the function to inactivate the desktop worked for the primary monitor, but not the secondary.
GeneralRe: Pretty cool...memberJohn A. Johnson10 Nov '03 - 22:31 
Yes, I didn't analyze the multi-monitor option.
 
Looking here and there, I saw that it's possible to have some API's including the multimon.h file in the project.
 
Actually I work with a laptop, so I'm not able to test this feature.
 
Soon I'll post here a tip how to support a multimonitor system, but I have to ask someone to try the code form me... Roll eyes | :rolleyes:
 
Thank you.
 
Cool | :cool:
GeneralRe: Pretty cool...memberJohn A. Johnson11 Nov '03 - 2:24 
Hi Benjaminl,
 
ok, I have found this solution, but I can't test it.
 
include this after the stdafx.h in the MakeInactiveDlg.cpp file:
 
#pragma warning(disable: 4706)
#define COMPILE_MULTIMON_STUBS
#include <multimon.h>
#pragma warning(default: 4706)
 
Ok then, substitute the OnMakewininactive() button call this way:
 
void CMakeInactiveDlg::OnMakewininactive() 
{
	if (GetSystemMetrics(SM_CMONITORS) > 0)
	{
		HMONITOR hMonitor =
			MonitorFromWindow(
				GetDesktopWindow()->GetSafeHwnd(),
				MONITOR_DEFAULTTONEAREST);
 
		MONITORINFO mi;   mi.cbSize = sizeof(mi);
		GetMonitorInfo(hMonitor, &mi);
 
		CRect rcMon = mi.rcMonitor;
 
		CFadeWnd wndFade;
		wndFade.Create(
			GetDesktopWindow(),
			false,
			rcMon);
	}
	else
	{
		CFadeWnd::AutoFade(GetDesktopWindow());
	}
}
 
And please, let me know it if works...
 
Cool | :cool:
 
[edited]
GeneralRe: Pretty cool...memberbenjaminl11 Nov '03 - 6:06 
That didn't do it. The desktop of the primary monitor now fades to grey, then becomes active again. I don't have too much time to spend on it now. Don't worry about it though. My apps usually have to reside on single monitor systems anyway, I just thought it'd be great if my dev system acted the same way.
 
Thanks again.
 

GeneralRe: Pretty cool...memberJohn A. Johnson11 Nov '03 - 9:45 
http://www.codeproject.com/cpp/multimon.asp[^]
 
Now I have to write 1000 times on the blackboard: “I have to search in the CODEPROJECT... I have to search in the CODEPROJECT... I have to search in the CODEPROJECT... I have to search in the CODEPROJECT... I have to search in the CODEPROJECT... I have to search in the CODEPROJECT... I have to search in the CODEPROJECT...“
 
Roll eyes | :rolleyes:
GeneralSweetmemberRome Singh4 Nov '03 - 2:09 
This is one visual fx that's not over done.
GeneralRe: SweetmemberJohn A. Johnson4 Nov '03 - 8:33 
Cool | :cool:
GeneralYes, really sweet, butmemberPixiGreg10 Nov '03 - 8:48 
Yeah that rocks except the fading "on call" would be better if the call was not delayed.
 
p i x i g r e g
GeneralGreat, reminds me of VisagememberPatje3 Nov '03 - 20:47 
Nice article.
It reminds of the 80's song 'Fade To Gray' by Visage.
 
Enjoy life, this is not a rehearsal !!!


GeneralFade to any gradientmemberMikko Mononen3 Nov '03 - 12:06 
Since you are converting the image to a grey scale, you can fade to any gradient if you wish, let's assume you have an array which has the gradient (256 values of COLORREF). If you change your inner loop to this:
 

int iAlpha = (int)(dfTrans / 100.0f * 255.0f);
 
for (int i=0; i> 8;
 
// Take color from the gradient
COLORREF Col = clrGradient[iGrey]; // You may want to try claming here...
 
ptPixels[i] = RGB( (GetDibR( Col ) * iAlpha + iSrcR * (255 - iAlpha)) >> 8,
(GetDibG( Col ) * iAlpha + iSrcG * (255 - iAlpha)) >> 8,
(GetDibB( Col ) * iAlpha + iSrcB * (255 - iAlpha)) >> 8 );
}

 
you'll be able to fade to any gradient Smile | :)
 
By using integers and shifting to do the alpha fading you loose a bit here and there, but it will be very minor in this application (the problem is the 255 / 256 thing).
 

GeneralRe: Fade to any gradientmemberJohn A. Johnson3 Nov '03 - 21:52 
Great tip! Big Grin | :-D
Can I code it in the application?
 
This will make the code really flexible!
 
For the gray calculation accuracy, I've choose to use only the Green component because is the more significant in a gray conversion.... it was only a way to make the calculation a bit faster (70% accuracy).
 
But the way you is really well done, so performance is preserved. Big Grin | :-D
 
Cool | :cool:
GeneralPlay with the demomemberJOHN113 Nov '03 - 10:29 
First play:
0. Run the demo
1. Click on "Make this inactive" button
2. Right-click on the button dialog on task bar and click on "Move" menu
3. Move the window (the original dialog) using arrows on keyboard. You will see
2 windows side by side, the original with the real colours, and the CFadeWnd class created window (in fact, the created bitmap window)
 
Second play:
0. Run the demo
1. Click on "Make desktop inactive" button
2. To access the desktop, push on the Windows Logo touch keyboard for example
3. You will see two demo buttons on the task bar, one of them is the dialog (the original with caption) and the other one is the window created CFadeWnd class without caption
 
These 2 remarks may make the article more explicit and more comprehensible by all people.
 
Nice article
GeneralRe: Play with the demomemberJohn A. Johnson3 Nov '03 - 10:39 
Roll eyes | :rolleyes: Seems I have something to fix!
 
1. disable the parent window while the CFadeWnd is active
2. hide the taskbar icon
 
Thank you
 
Cool | :cool:
GeneralI have an idea !!memberWREY3 Nov '03 - 8:26 
This would be a great security tool if when the desktop (or any window for that matter of fact) looses focus or goes inactive, that the only way it can regain focus (and consequently, use of its functionality again) would be by "right clicking" on it and enter some sort of password.
 
As it is right now, when the desktop (or a window) looses focus (which is what happens when it goes inactive), all the user has to do, is click on the desktop (or the window) and it instantly regains focus (and usability) again, which means, other than the desktop temporarily going inactive, it doesn't seem to serve any other purpose!
 
Even Screen saver comes on when the desktop is inactive, and I can launch any program from a multiple of other places. IOW, the desktop going inactive doesn't really prevent me from doing anything!!
 
So, what purpose does it serve?
 
The only way I can give a beneficial answer to that, would be to coincide a temporary disabling of my machine with its fading (and it becoming inactive) until some purposeful event occurs that would make it regain usability and functionality when I want, and nobody else could. Then I could see when my desktop is disabled, I know my machine is also disabled (and secured) until I do something to remove that status from it.
 
Nevertheless, I see this article as a meaningful first step towards other possibilities, including promises of its worthwhile use in multithreading matters.
 
Wink | ;)
 
William
 
Fortes in fide et opere!
GeneralRe: I have an idea !!memberJohn A. Johnson3 Nov '03 - 10:41 
the original purpose for me, was to disable the window while a modal popup was over it.
 
Let me think a bit to easy implement your idea.
 
Thank you
 
Cool | :cool:
GeneralRe: I have an idea !!memberWREY11 Nov '03 - 9:54 
It didn't matter if the desktop was inactive, and it didn't matter if any of the mouse button was locked, I was able to do just about anything I wanted to on the computer, and run ANY program I wanted to, ... FROM ANYWHERE!!
 
I was even able to deactivate your sample (as it was running) or even kill it. NOTHING that your sample made inactive, or locked away, prevented access to other programs and files. The idea of modality was not preserved because I was able to circumvent that feature by running the same program that your sample wanted to prevent (from continuing to run) until a button (or some event) had transpired, by simply, RUNNING ANOTHER INSTANCE of the program!!
 
I am still at a lost as to what it is that you're trying to lock away, or prevent from happening, since I was able to conduct business as usual while those features from your sample were in place.
 
Another thing: It didn't matter if "Secured Lock on Left Mouse," meant that the right mouse button would still be usable, or if I had "Secured Lock on Right Mouse," that the left mouse button would still be usable. Locking any of them made BOTH unusable (as far as you may want to think Wink | ;) )
 
What I think you have here, is a sample with very good promises, but which hasn't FULLY achieved any!! It still remains a 'stepping stone'.
 
Unsure | :~
 
William
 
Fortes in fide et opere!
GeneralRe: I have an idea !!memberJohn A. Johnson11 Nov '03 - 10:32 
Hi William,
 
my objective was quite simple: lock a selected window that it becomes currently faded for the needing time.
 
In the origin, the routine was made for 256 color mode displays, to convert the dialog-windows that contain palette colored images in a gray scale while they don't have focus, to prevent screen flashing.
 
Then playing with the code, the result was this small CFadeWnd class. It was cute and I post it (even to make some experience writing my own article, as you know in previous emails, I have this dream to share something of mine).
 
To prevent multi-instances of the same application (or dialogs, or windows), it's a programmer choice and must be done at app-init level. A good solution is to lock new instances of an application, is to use a MUTEX; for sample (this comes from my ERP application):
 
BOOL CIRISApp::InitInstance()
{
	//	Check existing instance
	HANDLE hMutex = CreateMutex(NULL,FALSE,_T("IRIS"));
 
	// then check for that name whether it already exists or not by following code, 
	// if exists release mutex and return false otherwise just release the mutex
	if (hMutex  &&  GetLastError() == ERROR_ALREADY_EXISTS) 
	{
		ReleaseMutex(hMutex); 
		return FALSE; 
	} 
 
	ReleaseMutex(hMutex); 
...
 
To lock the whole computer in a secure way, the best choice (in my opinion) is the screen saver with a password. And probably there is an API call to invoke the screen saver activation directly without waiting the idle-delay time.
 
Believe me, your original idea is nice, and looking to my code, what was really missing, was a call inside the class, to keep the grey effect alive even after an invocation of a dialog (the password for sample if the input data was failed).
 
Another point that was important for me, was to give this fading effect to the people that doesn’t have Windows/XP or 2003. For sample, layered (transparency on a given color, and alpha blending) options, and some smart effects are not available in previous Windows versions, and probably soon I’ll post some tips to do these effects too.
 
Cool | :cool:

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 10 Nov 2003
Article Copyright 2003 by John A. Johnson
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid