在WPF应用程序中禁用Aero Peek

时间:2011-05-28 06:46:28

标签: wpf pinvoke dwm aero-peek

我想在我的WPF应用程序中禁用Aero Peek(当用户将鼠标放在“显示桌面”按钮上时,我的应用程序必须可见)。我使用这个PInvoke签名:

[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_LAST
}

[Flags]
public enum DWMNCRenderingPolicy : uint
{
    UseWindowStyle,
    Disabled,
    Enabled,
    Last
}

[DllImport("dwmapi.dll", PreserveSig=false)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DwmIsCompositionEnabled();

[DllImport("dwmapi.dll", PreserveSig=false)]
public static extern Int32 DwmSetWindowAttribute(IntPtr hwnd,
                                                 DwmWindowAttribute dwmAttribute,
                                                 IntPtr pvAttribute,
                                                 uint cbAttribute);

这个用法:

    var helper = new WindowInteropHelper(this);
    helper.EnsureHandle();

    if (API.DwmIsCompositionEnabled())
    {
        var status = Marshal.AllocCoTaskMem(sizeof(uint));
        Marshal.Copy(new[] {(int) API.DWMNCRenderingPolicy.Enabled}, 0, status, 1);
        API.DwmSetWindowAttribute(helper.Handle,
                                  API.DwmWindowAttribute.DWMWA_EXCLUDED_FROM_PEEK,
                                  status,
                                  sizeof (uint));
    }

在我的64位系统(Windows 7 Professional)中,只有在运行64位应用程序时才能正常工作。如果我在WOW64模式下运行32位应用程序,我会收到异常:

“对PInvoke函数'XXX :: DwmSetWindowAttribute'的调用使堆栈失衡。这可能是因为托管PInvoke签名与非托管目标签名不匹配。检查调用约定和PInvoke签名的参数匹配目标非托管签名。“

您如何看待这个?解决方案是什么?

1 个答案:

答案 0 :(得分:6)

我更改了签名:

[DllImport("dwmapi.dll", PreserveSig = true)]
public static extern int DwmSetWindowAttribute(IntPtr hwnd,
                                               DwmWindowAttribute dwmAttribute,
                                               IntPtr pvAttribute,
                                               uint cbAttribute);

和用法:

if (API.DwmIsCompositionEnabled())
{
    var status = Marshal.AllocHGlobal(sizeof(int));
    Marshal.WriteInt32(status, 1); // true
    API.DwmSetWindowAttribute(helper.Handle,
                              API.DwmWindowAttribute.DWMWA_EXCLUDED_FROM_PEEK,
                              status,
                              sizeof(int));
}