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

Making any application transparent in Windows 2000/XP

By , 7 Jul 2003
 

Introduction

There are many articles that demonstrate how you can use the new layering features of Windows 2000 or Windows XP to create applications that are translucent. This article adds to that and shows how you can use the same features to turn any application transparent even if you do not have sources for it.

Using this "WinTrans" application you will be able to select any currently running application and turn it transparent by dragging and dropping the wand (icon at the top-left corner) on the title bar of that application. You can also control the transparency using the slider. "WinTrans" has an interface very much like SPY and also demonstrates the usage of Win32 APIs to locate a window under the mouse pointer and extract details like the class associated with it, the caption of the window, etc.

"WinTrans" comes in handy if you want to work on a maximized window and at the same time keep a watch on some other application running in the background.

Background

In Windows 2000 and Windows XP a new function named SetLayeredWindowAttributes has been added to User32.dll. To use this function an application needs to set the WS_EX_LAYERED (0x00080000) bit in the window style either while creating it or later using the SetWindowLong function. Once this bit is set any application can call this function passing a handle to a window and make either the whole window or a particular color on the window transparent. This function takes the following arguments.

  • HWND hWnd: Handle to the window
  • COLORREF col: Color to be made transparent
  • BYTE bAlpha: If this value is 0 the window becomes completely transparent and if it is 255 it becomes opaque
  • DWORD dwFlags: If this flag is 1 then only the color col is made transparent. If it is 2 then the whole window becomes transparent as dictated by the bAlpha value

Using the code

We begin by defining the following member variables of the main dialog class in WinTransDlg.h

bool m_bTracking;   //  will be true when the mouse is 
                    //  being tracked
HWND m_hCurrWnd;    //  Handle to the window over which 
                    //  the mouse was last present
HCURSOR m_hCursor;  //  The wand cursor

We also define a function pointer that points to the SetLayeredWindowAttributes function. This function is defined in the User32.dll.

//  Global definition
typedef BOOL (WINAPI *lpfn) (HWND hWnd, COLORREF cr, 
              BYTE bAlpha, DWORD dwFlags);
lpfn g_pSetLayeredWindowAttributes;

In the OnInitDialog event handler for the dialog we get the address of the SetLayeredWindowAttributes function and store it in g_pSetLayeredWindowAttributes. We also load the wand cursor and store the handle in m_hCursor

BOOL CWinTransDlg::OnInitDialog()
{
    ....
    //  get the function pointer for SetLayeredWindowAttributes 
    //  in User32.dll
    HMODULE hUser32 = GetModuleHandle(_T("USER32.DLL"));
    g_pSetLayeredWindowAttributes = (lpfn)GetProcAddress(hUser32,
               "SetLayeredWindowAttributes");
    if (g_pSetLayeredWindowAttributes == NULL)
        AfxMessageBox (
            "Layering is not supported in this version of Windows",
             MB_ICONEXCLAMATION);

    //  Load the wand cursor
    HINSTANCE hInstResource = AfxFindResourceHandle(
         MAKEINTRESOURCE(IDC_WAND), RT_GROUP_CURSOR);
    m_hCursor = ::LoadCursor( hInstResource, MAKEINTRESOURCE(IDC_WAND) );
    ...
}

We then define handler for the WM_LBUTTONDOWN, WM_LBUTTONUP and WM_MOUSEMOVE events. For the handler for WM_LBUTTONDOWN we do the following

void CWinTransDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
    ...
    SetCapture();      // make mouse move events to 
                       // be directed to this window
    m_hCurrWnd = NULL; // Currently no window is to be made transparent
    m_bTracking = true;     // set the tracking flag
    ::SetCursor(m_hCursor); // turn the mouse pointer into the wand cursor
    ...
}

For mouse move event handler the following code is used

void CWinTransDlg::OnMouseMove(UINT nFlags, CPoint point)
{
    ...
    if (m_bTracking)
    {
        ...
        //  convert mouse coordinates to screen
        ClientToScreen(&point);
        ...
        //  get the window at the mouse coords
        m_hCurrWnd = ::WindowFromPoint(point);
        ...
        // Show details of the window like class, caption, etc.
        ...
    }
    ...
}

As long as the left mouse button is clicked anywhere inside the main dialog and is not released the mouse pointer will change into the wand and the details of the window beneath the pointer will be displayed on the WinTrans dialog

When the button is released the event handler for WM_LBUTTONUP is called.

void CWinTransDlg::OnLButtonUp(UINT nFlags, CPoint point)
{
    ...
    //  stop tracking the mouse
    ReleaseCapture();
    m_bTracking = false;

    //  If the window under the mouse is not of this 
    //  application we toggle its
    //  layer style flag and apply the alpha as set by the slider control
    if (g_pSetLayeredWindowAttributes && m_hCurrWnd != m_hWnd)
    {
        ::SetWindowLong(m_hCurrWnd, GWL_EXSTYLE,
                        GetWindowLong(m_hCurrWnd, 
                        GWL_EXSTYLE) ^ WS_EX_LAYERED);
        g_pSetLayeredWindowAttributes(m_hCurrWnd, 0,
                        (BYTE)m_slider.GetPos(), LWA_ALPHA);

        ::RedrawWindow(m_hCurrWnd, NULL, NULL,
                       RDW_ERASE | RDW_INVALIDATE | 
                       RDW_FRAME | RDW_ALLCHILDREN);
    }
    ...
}

Points of Interest

This application works correctly only when the wand is dropped on the title bar of another application or on the body of a dialog based application. If for example the wand is dropped on the body of notepad it will not work

To remove the transparent effect you can simply drag-n-drop the wand again on that application. Since in OnLButtonUp we toggle the WS_EX_LAYERED bit the transparency effect will also be toggled

TransWand does not work on the command window

History

  • v1.0 This is the initial version.
  • v1.1 Added Undo All button and check box to clear the transparency effect on all windows when WinTrans is closed

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

abhinaba
Web Developer
United States United States
Member
I just love coding. I started programming in 1995 with BASIC and then moved through Cobol, Pascal, Prolog, C, C++, VB, VC++ and now C#/.NET.
 
I received a Bachelor of Technology degree in Computer Science from University of Calcutta in 2001.
 
I worked for some time in Texas Instruments, Adobe Systems and now in Microsoft India Development Center in the Visual Studio Team Systems.
 
I am from the City of Joy, Kolkata in India, but now live and code Hyderabad.

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   
GeneralMy vote of 5memberrunafterfree19 Jul '12 - 16:47 
nice example for study layer window
GeneralWindows 7 transparencymemberScott Sucher29 Jul '10 - 14:06 
Had WinTrans 1.0 on Vista, necessary for my research to overlay one window on top of another, both transparent. Upgraded to Windows 7, this capability has gone away. Anyone have suggestions on how to make the entire window transparent (just as in WinTrans)?
 
Scott
And if you could respond to scott@museumdiamond.com, I would be very grateful as I'm not sure I can find this site again.
GeneralWindows 7 total transparency of open windowsmemberScott Sucher29 Jul '10 - 14:05 
Had WinTrans 1.0 on Vista, necessary for my research to overlay one window on top of another, both transparent. Upgraded to Windows 7, this capability has gone away. Anyone have suggestions on how to make the entire window transparent (just as in WinTrans)?
 
Scott
And if you could respond to scott@museumdiamond.com, I would be very grateful as I'm not sure I can find this site again.
Generalworks like a charmmembercap3327 Jul '10 - 21:37 
Great little tool!
 
abhinaba, are you still around here?
I wonder if you would mind if I use your demo app for a little project?
(absolutely non-commercial, BTW Smile | :)
 
cap
GeneralNice, windows bordermemberaddictive7 Nov '08 - 7:15 
Nice demo!
 
Is there a way to modify the code so that the selected window can have the window-border & window-menu hidden?
 
Thanks in advance to teh windows hWnd hackers out there!
GeneralNice demomemberAnil K P9 Dec '07 - 22:55 
Good work man
Generaldifficult problem for mememberuy quoc5 Dec '06 - 23:20 
I have got a problem :How must I do to capture desktop by use SDI (single Document Interface)? can you help me? thank you very much!Smile | :) Smile | :) Smile | :)
 
Thanks u very much

GeneralHelp me!memberuy quoc3 Dec '06 - 22:34 
I've got some problems with my program. I used SetLayerredWindowAttributes(...),SetWindowLong(...) but errors occur with content:"WS_EX_LAYERED is undefined" ,"LWA_ALPHA is undefined", . Must i do? I'm very like your article with excillent content, but I can't apply it to my program. I need help!Cry | :((
 
Thanks u very much

GeneralRe: Help me!membercutebug4 Dec '06 - 16:11 
Use the following definition
 
#define WS_EX_LAYERED 0x00080000
#define LWA_COLORKEY 0x00000001
#define LWA_ALPHA 0x00000002
#define ULW_COLORKEY 0x00000001
#define ULW_ALPHA 0x00000002
#define ULW_OPAQUE 0x00000004
 


 
Cutebug Wink | ;-)

GeneralRe: Help me!memberuy quoc5 Dec '06 - 14:14 
thanks so lot, Cutebug! you're Roll eyes | :rolleyes: great!
 
Thanks u very much

QuestionIs there any possible way to change Edit Box Or Forms Caption?membersis138228 Jul '06 - 21:48 
Hi, Your Work is very Nice And readable but i am wondering if it is possible to change the other Applications Edit Box Or Forms Caption Or Text in this Way If yes How? ThanksSigh | :sigh:
Generalbehind transparencymemberRobsori12 Jun '06 - 22:56 
I've got a dialogue type application programme maximizate(extended all over the screen) on which I adjust on my way the transparency. My intention is to make this dialogue to act as a masque that meens that the mouse arrow to action in behind of it and to ignore any control by the dialogue. The dialogue behave like a window in which I can see the mouse arrow action on the aplication ruled behind.Is there any way to do something like this?
 
Thank you.
GeneralRotating a dialog 90 degreesmemberAlexEvans11 Jan '06 - 10:04 
Hi there
 
What if I need to create a VERTICAL dialog... That is - my caption bar is on the left (or on the right), my text is all vertical, the button's text is also vertical, and - the tab stop order is vertical... and the text type in the edit boxes... vertical too
 
Can this be done?
 
Cheers
Alex

GeneralRe: Rotating a dialog 90 degreesmemberabhinaba12 Jan '06 - 5:43 
Everything is possible, but the question is how difficult it is Smile | :)
 
Windows (or any OS UI subsystem) does not support this. To get this done you need to implement custom drawing for everything. This includes Dialogs, static, text box, ... everything you can possibly think of except progress bar which supports vertical orientation. I am a bit curious though, why on earth do you need this???
 
==========================
AB => Code and let code
Go to my home
==========================
GeneralRe: Rotating a dialog 90 degreesmemberAlexEvans12 Jan '06 - 14:30 
I suspected this to be the case, I will have no choice but use the Monitor / video card driver to do this for me…
 
Now – why do I want this??? Good question
 
Some sales people in our office thought this to be a “Smart” idea for a large Plasma screen – 42” to be standing up (in portrait) and have an application running in the bottom half, and some banner advertising on the top half.
 
So for the development stage, I wanted to be able and program at my desk and NOT have to work with the huge display in front of me…
 
Cheers
Alex

GeneralOne suggestionmemberPravinSingh22 Aug '05 - 21:24 
First of all, this is AWESOME. Great work !!
My vote:
5 for the Idea
4 for Usability
5 for Simplicity
5 for Presentation
 
I have one suggestion. Since I am a bit too lazy to open WinTrans first, click on the wand and then drag it, I think it would be easier if I can have WinTrans in my quick launch and directly drag the icon of WinTrans itself in place of the wand (or somehow place the wand in quick launch/system tray). That would save me some mouce clicks (lazy me) Smile | :)
 
Regards,
Pravin.
GeneralRe: One suggestionmemberabhinaba23 Aug '05 - 1:06 
I guess making it easy to use should be possible by installing global short cut hooks like WinKey+T to increase transparency. Or extending the system menu. But the way you suggested would be difficult.
 
This is because the Quick Launch stores the shortcuts to applications and dragging dropping them on other window has valid meaning of moving aroung shortcuts, so I'd rather not meddle with this.
 
However, I just loved the idea of dragging and droping it from the system tray. You can catch mouse down event on your icon in the tray, change the mouse cursor and again find the window on which the user drops the cursor (mouse-up event) and apply the effect. This is very novel way of doing this. The only flip-side is that this is not discoverable feature. This means that user will not be able to figure this out by himself as this is not a very convetional way of doing such actions.
 
I am working on a post on System tray based applications and I think I'll add this to that post. With the amount of work pending on my plate I guess the ETA is Doomsday + 1
 
==========================
AB => Code and let code
Go to my home
==========================
Generalhiding the cursormemberleojose3 Jun '05 - 20:39 
can we do the same with the cursor also?
GeneralThere is one serious error in codememberslawek -- -6 Sep '04 - 5:45 
::SetWindowLong(m_hCurrWnd, GWL_EXSTYLE,
GetWindowLong(m_hCurrWnd,
GWL_EXSTYLE) ^ WS_EX_LAYERED);
 
I think you should use '|' operator instead of '^'. If you call that function above several times with '^' - EX_ style will become damaged.
 

 
http://cieszyn.xx.pl ->Forum Slaska Cieszynskiego
GeneralRe: There is one serious error in codememberabhinaba6 Sep '04 - 18:56 
The purpose of
::SetWindowLong(m_hCurrWnd, GWL_EXSTYLE, GetWindowLong(m_hCurrWnd, GWL_EXSTYLE) ^ WS_EX_LAYERED);
 
is to toggle the WS_EX_LAYERED flag. So that when you drop the wand on a window for the first time it will become transparent and the second time it will become opaque.
 
==========================
AB => Code and let code
Go to my home
==========================
GeneralRe: There is one serious error in codememberslawek -- -7 Sep '04 - 8:55 
Ah sorry. I didnt read the code careful enough.
Generalwhy SetLayeredWindowAttributes can't used in 8bits(256) color qualitymemberwhizzkid@ms28.hinet.net11 Aug '04 - 4:27 
who can solve this problem...
why SetLayeredWindowAttributes can't used in 8 bits(256) color quality.
please tell me, thanks.

GeneralPocket PCmemberpratik67821 May '04 - 4:14 
Hi AB,
 
This is great, but i want to do something similar on Pocket PC. Do you think i would be able to do this. Or if you can point me to right directions.
 
Thank You,

 
******************************
Pratik Parikh
Computer Science Club(webmaster)
******************************

GeneralRe: Pocket PCmemberabhinaba21 May '04 - 19:05 
What I know is that the APIs I have used are only available on WinNT/2K or later. I do not think they work on WinCE.
 
==========================
AB => Code and let code
Go to my home
==========================
Questiondoesn't work on cmd.exe window ?membervladimirz27 Mar '04 - 19:34 
First of all, very good.
Can you check why it doesn't work on cmd.exe window.
 
vladz
Generalnice goingmembert2di4u14 Mar '04 - 1:33 
many thanks,
Questioncan anyone give me a source code for a windowsmemberbuck16 Nov '03 - 9:21 
can any body give me a code for a window with a
textbox and when they enter it a new window appears with the text in it
there is a source in visual basic but i havent got visual basic so can you put it in c or c++
thank you
danny
GeneralPerfectmembergsake17 Jul '03 - 8:02 
It's a perfect code....
GeneralWorks not with command line windowmemberKnut Beese10 Jul '03 - 0:05 
This very nice utility works not with command line windows (command or cmd). Why? I thought the boxes are only containers for the command interpreter and work like any other.
GeneralRe: Works not with command line windowmemberabhinaba13 Jul '03 - 19:08 
I have noticed it does not work with the command window. I have mentioned it in the article as well in the "Points of Interest" section. I have no clue why it does not work.
 
==========================
AB -> Enjoy!!
==========================
GeneralRe: Works not with command line windowmemberKnut Beese13 Jul '03 - 22:06 
Sorry. Think I didn't read it carefully enough.
 
Regards
Knut
GeneralBlurred Image - hit ctrl-refresheditorNishant S8 Jul '03 - 12:29 
If anyone gets a blurred image it's the old one from the cache. Please hit ctrl-refresh to get the new image
 
Nish
 

"I'm a bit bored at the moment so I'm thinking about writing a new programming language" - Colin Davies
 
My book :- Summer Love and Some more Cricket [New Win]
Review by Shog9 Click here for review[NW]

GeneralSimple and perfect!membermanos_crete8 Jul '03 - 7:20 
Very nice work, congratulations! Smile | :)
 
--- Manolis from Crete ---
Generalhttp://www.codeproject.com/w2k/trans.aspsussAnonymous7 Jul '03 - 7:44 
If this article gets 5, I think below should be 5+....Rose | [Rose]
http://www.codeproject.com/w2k/trans.asp
GeneralRe: http://www.codeproject.com/w2k/trans.aspmembercadinfo8 Jul '03 - 4:37 
Posted 2 Jul 2003 .VS. Posted 12 Aug 2000
-------------------------------------------
hehe, but ab has magic wandRose | [Rose]
 
Smile | :)
GeneralExcellent!memberNikolai Teofilov7 Jul '03 - 7:30 
My 5!
Brilliant!
Cool | :cool:
GeneralYou dog - there goes my afternoonmemberJim Crafton7 Jul '03 - 6:52 
Man there goes the rest of the day. Obviously I am going to to have to "test" all my different windows with this in the name of furthering knownledge...
Good thing I am completely bored today... Smile | :)
 
Great job!
 
¡El diablo está en mis pantalones! ¡Mire, mire!
 
Real Mentats use only 100% pure, unfooled around with Sapho Juice(tm)!
GeneralThis is soooo cooool !!memberWREY3 Jul '03 - 10:20 
You have exceptional talents!! Cool | :cool:
 
Not only have you accomplished this work in a single dialog class, but looking through your code, I see 100%, pure, unadulterated talent.
 
I'm not just talking about what you may have accomplished with a (magic) wand, but more about the application of the technique you used, and the promotion of the idea in other ways.
 
My hat off to you!!!
 
The one thing I might suggest, is when the person exits the dialog, that the layering effect (or the magic spell Wink | ;) ) on those other applications whose title bar were used, that they be returned to their normal state.
 
As it is right now, you have to specifically undo the spell with the wand before exiting, otherwise, if you were to forget and exit the dialog, the spell remain in effect, causing you to reactivate the dialog and return to the application with the magic wand, in order to (break the spell and) restore them back to their normal state.
 
Cool | :cool: Cool | :cool:
 

William
 
Fortes in fide et opere!
GeneralRe: This is soooo cooool !!memberabhinaba3 Jul '03 - 19:46 
Thanks for the great comment. You are right. I thought of removing the spell when WinTrans closes. But WinTrans is old and forgetful so it only remembers the last person on which it casts the spell. So when WinTrans closes it needs to loop through all the open applications and reset the layering attribute in it. I was a bit too lazy to write that code.
 
On the otherhand I thought for people running a bit low on RAM they would like to cast the spell and then kick WinTrans out of their system. Though WinTrans does not like it, he can live with it Smile | :)
 
==========================
AB -> Enjoy!!
==========================
GeneralRe: This is soooo cooool !!memberWREY3 Jul '03 - 21:36 
You speak of WinTrans as though IT is in control. Such statements are indeed symptomatic of a lazy person, but greatness is never achieved by being lazy
 
That you somehow want to make it sound altruistic that it was because you thought of others running low on RAM why you didn't let WinTrans undo its layering, is irrelevant, since that only brings up another precaution you could have taken by monitoring the amount of RAM getting consumed so that the person running WinTrans could see for him/herself how close he/she might be running out of memory. I didn't think of that, but since you were aware of it and did NOTHING in that respect, points out another deficiency you ought to correct.
 
I do not see the point about someone running low on RAM, "would like to cast the spell and then kick WinTrans out of their system," as being a good reason for not letting the dialog undo its own layering, since it speaks directly to the problem I originally broached; that being, WinTrans should be the one to "undo" its own spell whenever the person exits the dialog. The person should NOT be the one to have to undo WinTrans' layerings. Upon exiting, WinTrans should do that itself, which means if it needs to store handles or pointers of each window it layered, then so be it; it should do it. To admit that you were lazy as the reason why it didn't get done, is not a good excuse.
 
Take responsibility and don't make it sounds as though your program is in charge.
 
Wink | ;)

 
William
 
Fortes in fide et opere!
GeneralRe: This is soooo cooool !!memberabhinaba4 Jul '03 - 0:28 
I was just joking about the spell, lazyness and all!!!
I had no idea that you would get so worked up about that Frown | :(
 
It is easy to add code to undo the effect. I wrote the code to demonstrate how layering effect and getting information about other windows on the system works. Once that was done I did not think of adding additional stuff to it.
 
I think the best option would be to add a check box labeled "Remove transparencies from all windows when closed".
 
==========================
AB -> Enjoy!!
==========================
GeneralNever mind.memberWREY4 Jul '03 - 0:46 
If you feel I was getting "worked up," then I retrack everything I said, because I, too, was only joking.
 
You are correct! WinTrans is great the way it is, and doesn't need anything more done to it.
 
William
 
Fortes in fide et opere!
GeneralRe: Never mind.memberabhinaba4 Jul '03 - 2:07 
I liked your feedback and have actually updated and resubmitted the application.
 
I have added a Undo All button and a check box that can be used to Undo the effect once the application is closed.
 
Before the changes are updated on CodeProject after review you can take a look at the application from here
 
The only difference being the application at the above link has a about box the one on CodeProject does not have that.
 
Your feedbacks are most welcome!!!
 

 
==========================
AB -> Enjoy!!
==========================
GeneralCould not review what you did.memberWREY4 Jul '03 - 8:32 
The web address you provided did not allow me access (said something about, "Page not allowed for viewing.").
 
The whole idea of specifically putting a button on the dialog for the unlayering of windows to be done, is NOT necessary. The viewer should not be the one to indicate that they want unlayering. The application should automatically do the unlayering when it's about to exit.
 
Simply go into CWinTransApp::InitInstance() and just before you "Return", add an "if" condition to detect when the person has clicked the "OK" or "Close" button. At that point is when WinTrans should go into action and unlayer the various windows it did. Upon completion of that activity is when it then exits!!

 
William
 
Fortes in fide et opere!
GeneralRe: Could not review what you did.memberslawek -- -6 Sep '04 - 6:37 
I have one question. I heard that windows reuses HWND handles so is there any solution to indentify windows made transparent with wintrans?
 
http://cieszyn.xx.pl - Forum Slaska Cieszynskiego
GeneralRe: Could not review what you did.memberabhinaba6 Sep '04 - 19:01 
You can enumerate all windows using something like EnumWindows and check the WS_EX_LAYERED flag of each of the windows to see which is transparent.
 
==========================
AB => Code and let code
Go to my home
==========================
GeneralRe: Could not review what you did.memberslawek -- -7 Sep '04 - 8:50 
Yes but other applications can also have windows with WS_EX_LAYERED. There are some applications that use transparent topmost windows. For example DialUPMeter.
 
I know that chance that window you set transparent will get destroyed and then another window with WS_EX_LAYERED reuse its handle is very little, but it exists Wink | ;)
GeneralThat's ...memberRage3 Jul '03 - 0:49 
... simply awesome. My 5. Cool | :cool:
 
~RaGE();

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 8 Jul 2003
Article Copyright 2003 by abhinaba
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid