Monday, March 23, 2009

WPF like effects in your Win32 forms

Are you still developing native applications? Would you like to do some cool tricks with your forms? How about making your windows fade in and out?

The Win32 API to the rescue! The function AnimateWindow can be used to blend in and out the form. To the FormShow event handler, add the following code :

AnimateWindow(Self.Handle, 1000, AW_ACTIVATE or AW_BLEND);

To reverse the effect, add the following code to the FormClose event :

AnimateWindow(Self.Handle, 1000, AW_HIDE or AW_BLEND);


You can also get the form to slide in, rather than blend, by changing the flags to AW_SLIDE or AW_HOR_POSITIVE to get the slide to come in from the left for example.



The same approach can be used in Delphi Prism, when using WinForms. While Delphi Win32 imports the AnimateWindow method for you, in windows.pas, in Delphi Prism you have to do it yourself using P/Invoke. (As you would with C# or VB.NET may I add). So in your WinForm, add the following code to the private declaration :



private
const AW_HIDE = $10000;
const AW_ACTIVATE = $20000;
const AW_HOR_POSITIVE = $1;
const AW_HOR_NEGATIVE = $2;
const AW_SLIDE = $40000;
const AW_BLEND = $80000;
[DllImport("user32.dll", CharSet := CharSet.Auto)]
class method AnimateWindow(hwand : IntPtr; dwTime : Integer; dwFlags : Integer) : Integer;external;


Remember to add System.Runtime.InteropServices to the uses clause of your form. Now, you can add the same code as before (it's all object pascal, so the same syntax), to the Load and FormClosing events of your form.



  method MainForm.MainForm_Load(sender: System.Object; e: System.EventArgs);
begin
AnimateWindow(Self.Handle, 1000, AW_ACTIVATE or AW_BLEND);
end;

method MainForm.MainForm_FormClosing(sender: System.Object; e: System.Windows.Forms.FormClosingEventArgs);
begin
AnimateWindow(Self.Handle, 1000, AW_HIDE or AW_BLEND);
end;

So there you have it, forms that fade in and out.

No comments: