Fading Windows by Seth Willits
01-07-06




I cooked up an example project for someone using a slider and a button to fade in and out a window for a certain lenth of time. I morphed that into this project which automatically fades in and out a window when it is shown or hidden. I don't think you should use this for ever application or even many, but in the chance where you have one where a window needs to fade in (like a global floating window for a background task) here is how you can do it.



This is one window fading out above another opaque window.



Setup

First, add a new class called FadeWindow (a Window subclass) and then add a constant kFadeLength = 0.06 as a number. Next add a Close event definition, and then follow the steps below.


Fading In

There's a Carbon function called SetWindowAlpha which sets the translucency of a window with a value from 0 (transparent) to 100 (opaque). So all our window fading has to do is loop for a certain length of time (under 0.1 seconds is good) and linearly change the value from 0 to 100 to fade in. We do that like so:


Sub FadeIn()
  #if TargetMachO then
    Declare Sub SetWindowAlpha Lib "Carbon" (WindowRef as Integer, alpha as Single)
  #elseif TargetCarbon then
    Declare Sub SetWindowAlpha Lib "CarbonLib" (WindowRef as Integer, alpha as Single)
  #endif
  
  dim startTime, endTime as Double
  
  // Fade In
  startTime = Microseconds
  endTime = startTime + (kFadeLength * 1000000)
  while Microseconds < endTime
    SetWindowAlpha self.Handle, (Microseconds - startTime) / (endTime - startTime)
  wend
End Sub						


FadeIn is called from the Show method after calling the superclass's show method so the window actually shows up first.


Sub Show()
  Super.Show
  FadeIn
End Sub


Similarly, we call FadeOut from the Close event (not the method since it calls CancelClose and does some other things).


Sub Close()
  FadeOut
  Close
End Sub


And then the fade out code is the same as fade in, but there's a "1.0 - " in front of the alpha parameter to flip the value from going from 0 to 100 to 100 down to 0.


Sub FadeOut()
  #if TargetMachO then
    Declare Sub SetWindowAlpha Lib "Carbon" (WindowRef as Integer, alpha as Single)
  #elseif TargetCarbon then
    Declare Sub SetWindowAlpha Lib "CarbonLib" (WindowRef as Integer, alpha as Single)
  #endif
  
  dim startTime, endTime as Double
  
  // Fade Out
  startTime = Microseconds
  endTime = startTime + (kFadeLength * 1000000)
  while Microseconds < endTime
    SetWindowAlpha self.Handle, 1.0 - (Microseconds - startTime) / (endTime - startTime)
  wend
End Sub



Finished

That's all there is to it. There's . Download the project.