Search code examples
c#windows-10pinvokedwm

DwmSetWindowAttribute does not work with DWMWA_CLOAK


I recently started using lower level windows APIsn with C# for an application prototype and I stumble upon a problem that I cannot get my way around: Consider the following piece of code:

public class dW
{
    [DllImport("dwmapi.dll")]
    public static extern int DwmSetWindowAttribute(IntPtr hwnd, DwmWindowAttribute dwAttribute, ref int pvAttribute, int cbAttribute);

    [Flags]
    public enum DwmWindowAttribute : uint
    {
        DWMWA_NCRENDERING_ENABLED = 1,
        DWMWA_NCRENDERING_POLICY,
        DWMWA_TRANSITIONS_FORCEDISABLED,
        DWMWA_ALLOW_NCPAINT,
        DWMWA_CAPTION_BUTTON_BOUNDS,
        DWMWA_NONCLIENT_RTL_LAYOUT,
        DWMWA_FORCE_ICONIC_REPRESENTATION,
        DWMWA_FLIP3D_POLICY,
        DWMWA_EXTENDED_FRAME_BOUNDS,
        DWMWA_HAS_ICONIC_BITMAP,
        DWMWA_DISALLOW_PEEK,
        DWMWA_EXCLUDED_FROM_PEEK,
        DWMWA_CLOAK,
        DWMWA_CLOAKED,
        DWMWA_FREEZE_REPRESENTATION,
        DWMWA_LAST
    }

    public IntPtr Handle { get; private set; }

    public void HideWindow()
    {
        int value = 0x01;
        int hr  = DwmSetWindowAttribute(Handle, DwmWindowAttribute.DWMWA_CLOAK, ref value, Marshal.SizeOf(typeof(int)));
    }
}

Consider that Handle is a well defined IntPtr. I'm trying to Cloak a window using DwmSetWindowAttribute but for some strange reason it never works (the window remains visible all the time), and the result (stored in hr) is always -2147024891. I simply do not understand why this happens, since the code seems the be correct (imho). Do you have any clues?

Thanks


Solution

  • I got the same result (access denied) too, even with Admin, and I figured out only system shell and application itself can set cloak, third-party process will be denied.