C# – Enable / Disable DWM Composition (Aero)

As a follow up for C# – Screen capture with Direct3D, here is how to enable and disable composition (Aero) on Windows Vista and Windows 7.

If you are attempting to capture screen contents on Vista/Windows 7 without using DWM (e.g. BitBlt or the Direct3D approach linked above) – it is necessary to first disable composition.

Simply disable when your application starts with a call to Spazzarama.ScreenCapture.DWM.Composition.EnableComposition(false);, and re-enable when your application closes: Spazzarama.ScreenCapture.DWM.Composition.EnableComposition(true);.

using System;
using System.Runtime.InteropServices;

namespace Spazzarama.ScreenCapture.DWM
{
    public static class Composition
    {
        const uint DWM_EC_DISABLECOMPOSITION = 0;
        const uint DWM_EC_ENABLECOMPOSITION = 1;

        [DllImport("dwmapi.dll", EntryPoint = "DwmEnableComposition")]
        extern static uint DwmEnableComposition(uint compositionAction);

        /// <summary>
        /// Enable/Disable DWM composition (aka Aero)
        /// </summary>
        /// <param name="enable">True to enable composition, false to disable composition.</param>
        /// <returns>True if the operation was successful.</returns>
        public static bool EnableComposition(bool enable)
        {
            try
            {
                if (enable)
                {
                    DwmEnableComposition(DWM_EC_ENABLECOMPOSITION);
                }
                else
                {
                    DwmEnableComposition(DWM_EC_DISABLECOMPOSITION);
                }

                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.