Click here to Skip to main content
15,887,676 members
Articles / Desktop Programming / Win32

Fading Forms and Setting Opacity Without Flicker Using the Layered Windows API

Rate me:
Please Sign up or sign in to vote.
3.58/5 (10 votes)
14 Oct 2009CPOL3 min read 60.8K   2.1K   44   25
Get more control over your forms opacity by manually creating a wrapper to the Layered Windows API

Introduction

Everyone has seen the Opacity property in the Visual Studio property inspector when a form is selected. But few people realize exactly how that works behind the scenes, or even how poorly it is implemented. Windows 2K Microsoft has used the Layered Window API to snazzy up the mouse cursor with a little transparent drop shadow. This is done in the same fashion as the opacity setting in .NET Windows Forms. When changing the opacity of a form via its opacity property, the form makes a Windows API call behind the scenes, yep that's right, its just a simple winAPI wrapper smashed into a single property. Obviously you lose a little control. Let's get some back.

Background

Before the .NET Framework, transparent windows were done the same way as they are now, It just took quite a few more lines of code. When setting the opacity to a value besides 100%, the .NET Framework makes a call to SetWindowLong and throws a flag to toggle on the WS_EX_LAYERED API. Layered windows are a very powerful tool, but we will be talking about just the simplest use of it, setting a forms's Opacity, afterward SetLayeredWindowAttributes is called, passing to it a byte value indicating the level of opacity. 0 for transparent and 255 for opaque.

Sounds simple enough, but, Windows doesn't like that change, when you make the transition between not layered and layered windows, your form flickers black. And that's not attractive. and every time you alter the opacity property between 100% and any other valid value, the switch is made and you run the almost inevitable chance of seeing the infamous black flicker.

The trick here is to just keep the form a layered window all the time, your form will use a little more system resources, but not enough to make a real difference. Your computer is already making hundreds of calls to the layered window API, just a few more won't make any significant differences.

Using the Code

Included in the source download is my class called DDFormFader. It's a Layered Window wrapper class that handles all the trouble for you! You simply construct it passing the Handle to the form you want to control the opacity of and they use its pubic functions to manipulate the transparency effects.

C#
DDFormsExtentions.DDFormFader FF; 
 public Form1()
  {
   InitializeComponent();

    //pass the class constructor the handle to the form
    FF = new DDFormsExtentions.DDFormFader(Handle);

    //set the form to a Layered Window Form
    FF.setTransparentLayeredWindow();

    //sets the length of time between fade steps in Milliseconds 
    FF.seekSpeed = 5;  
    
    // sets the amount of steps to take to reach target opacity    
    FF.StepsToFade = 8; 

    FF.updateOpacity((byte)0, false); // set the forms opacity to 0;

    Load += new EventHandler(Form1_Load);
   }

   void Form1_Load(object sender, EventArgs e)
    {
      FF.seekTo((byte)255); // fade the form to full 
                            //opacity on load, cleanly with no flicker.
    } 

You can easily change the form's opacity using the UpdateOpacity method, and fade to any opacity using the seekTo method.

But enough of that. Let's see the real code!

First we interlop the user32 methods responsible for setting the flags that make the magic happen:

C#
//gets information about the windows
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);

//sets bigflags that control the windows styles
DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

//changes flags that modify attributes of the
//layered window such as alpha(opacity)
[DllImport("user32.dll")]
static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey,
 byte bAlpha, uint dwFlags); 

And set up the flags you will need:

C#
//WS_EX constants
private const int GWL_EXSTYLE = (-20);
private const int WS_EX_LAYERED = 0x80000;
private const long LWA_ALPHA = 0x2L; 

Now we toggle on the Layered window style with a simple call to the setWindowLong function, followed by a call to SetLayeredWindowAtrributes where the 3rd param is a byte representing the level of opacity, 0 for transparent, 255 for Opaque, and any number in between. Much finer control than .NET's percent system.

C#
SetWindowLong(frmHandle, GWL_EXSTYLE, 
	GetWindowLong(frmHandle, GWL_EXSTYLE) ^ WS_EX_LAYERED);
SetLayeredWindowAttributes(frmHandle, 0, _currentTransparency, (uint)LWA_ALPHA);

To disable the Layered window and revert to a standard window, you simply call the SetWindowLong method again with the same params. The DDFormFader class included has more functionality and is completely commented. Thanks!

Points of Interest

One thing to note that threw me for a loop was immediately after calling setWindowLong it is necessary to call SetLayeredWindowAttributes. If it's not immediately after the form will stop painting correctly and crazy things will happen, just remember to call SetLayeredWindowAttributes on the very next line. Or of course just use my class, it handles it all for you. :)

History

  • Current Version 1.0 Original release

License

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


Written By
Software Developer
United States United States
I am a part time programmer, The more I learn, the more I need to learn, the best of which I will share here on codeproject!

Visit my site and blog

Comments and Discussions

 
QuestionHow to use in VB.Net Pin
RUrry3-May-10 6:33
RUrry3-May-10 6:33 
QuestionFor a form not shown in taskbar? Pin
l30to111-Feb-10 8:49
l30to111-Feb-10 8:49 
AnswerRe: For a form not shown in taskbar? Pin
Diamonddrake11-Feb-10 10:25
Diamonddrake11-Feb-10 10:25 
QuestionIt`s Great! Pin
avionov11-Nov-09 19:06
avionov11-Nov-09 19:06 
AnswerRe: It`s Great! Pin
Diamonddrake13-Nov-09 11:22
Diamonddrake13-Nov-09 11:22 
GeneralThorough and Well Written Pin
KentuckyEnglishman20-Oct-09 2:59
KentuckyEnglishman20-Oct-09 2:59 
GeneralRe: Thorough and Well Written Pin
Diamonddrake20-Oct-09 11:07
Diamonddrake20-Oct-09 11:07 
Generala few suggestions Pin
BillWoodruff16-Oct-09 2:16
professionalBillWoodruff16-Oct-09 2:16 
GeneralRe: a few suggestions Pin
Diamonddrake16-Oct-09 10:38
Diamonddrake16-Oct-09 10:38 
GeneralRe: a few suggestions Pin
BillWoodruff19-Oct-09 21:14
professionalBillWoodruff19-Oct-09 21:14 
GeneralRe: a few suggestions Pin
Tom Donchez2-Feb-10 8:15
Tom Donchez2-Feb-10 8:15 
GeneralI think there's a workaround with no need for interop Pin
User 113800015-Oct-09 12:42
User 113800015-Oct-09 12:42 
GeneralRe: I think there's a workaround with no need for interop Pin
Diamonddrake15-Oct-09 16:38
Diamonddrake15-Oct-09 16:38 
GeneralMessage Closed Pin
16-Oct-09 2:59
User 113800016-Oct-09 2:59 
GeneralRe: I think there's a workaround with no need for interop Pin
Diamonddrake16-Oct-09 10:30
Diamonddrake16-Oct-09 10:30 
GeneralMessage Closed Pin
16-Oct-09 12:43
User 113800016-Oct-09 12:43 
GeneralRe: I think there's a workaround with no need for interop Pin
Diamonddrake16-Oct-09 13:16
Diamonddrake16-Oct-09 13:16 
GeneralRe: I think there's a workaround with no need for interop Pin
Tom Spink19-Oct-09 21:49
Tom Spink19-Oct-09 21:49 
GeneralRe: I think there's a workaround with no need for interop Pin
Diamonddrake20-Oct-09 10:49
Diamonddrake20-Oct-09 10:49 
GeneralRe: I think there's a workaround with no need for interop Pin
Tom Spink20-Oct-09 21:31
Tom Spink20-Oct-09 21:31 
GeneralRe: I think there's a workaround with no need for interop Pin
Diamonddrake21-Oct-09 10:37
Diamonddrake21-Oct-09 10:37 
GeneralRe: I think there's a workaround with no need for interop Pin
Tom Spink21-Oct-09 11:16
Tom Spink21-Oct-09 11:16 
Diamonddrake wrote:
I get your point. But if you read the wiki on C# C# wikki you will see that C# is part of the ECMA standard but was created originally by Microsoft. And so was .net, prior to being added to the ECMA standard. This includes the CLI concept as it was orignially devleoped by mirosoft CLI wikki


But that's my point. I'm not arguing Microsoft originally created it... I'm really not! I'm just saying that an open-source implementation is not a bad thing. It's a very good thing...

Microsoft did not create the HTTP protocol, yet they have created an implementation of that protocol in web browers and servers alike. The same goes for NNTP, POP3, IMAP, etc. The alternative implementation of the CLI is the same thing.

Diamonddrake wrote:
Microsoft developed it all, in fact. Microsoft assisted mono's project extensivly with the Shared Source Common Language Infrastructure project where due to its licensing is not allowed in commercial products, but is a stripped down version of the source code of the .net framework CLI base.


Actually, if you've ever worked on Rotor, i.e. Microsofts "open" implementation of the CLR, then you can't contribute to the Mono project. So Rotor, in fact, doesn't help Mono at all.

Diamonddrake wrote:
I have an open mind, and Linux is pretty cool, I don't knock it. I in fact have a laptop with a ubuntu partition. I just really like windows XP.
and as a MS.net developer, I target the MS .net framework.


That's good to know. I myself use Ubuntu exclusively, and I'm not ashamed to admit I have Windows Vista in a virtual machine to test my creations on.

However, as you've just said, you target the MS .NET framework - and targetting the framework means not using P/Invoke calls - that's targetting the operating system. So, if you write your application exclusively with the .NET framework in mind, it will already run without problems (generally) on Mono.

I'm currently the project leader for a group of developers writing a bespoke enterprise software product. It's a very complicated product... it's distributed, makes heavy use of reflection for the back-end database framework, has a very rich front-end. And it's written with only framework classes.

It works perfectly on Linux and Windows - to be honest, I haven't tested it on a Mac. And this makes me happy, because now I can reach much more people than if I was selfis, and wrote it only with Windows in mind.

-- Tom Spink

GeneralRe: I think there's a workaround with no need for interop Pin
Diamonddrake21-Oct-09 13:17
Diamonddrake21-Oct-09 13:17 
GeneralSounds like that would fix another annoyance Pin
supercat915-Oct-09 8:18
supercat915-Oct-09 8:18 
GeneralRe: Sounds like that would fix another annoyance Pin
Diamonddrake15-Oct-09 10:08
Diamonddrake15-Oct-09 10:08 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.