Setting/removing CS_DROPSHADOW style for a WinForm

2019-08-17 01:27发布

问题:

How to do that? I could not find any useful sample for C#. I know I should use SetClassLong/SetClassLongPtr, but here is the definition I only found: http://www.pinvoke.net/default.aspx/user32/SetClassLongPtr.html.

Obviously, I should call GetClassLongPtr with GCL_STYLE to read the current style flags, add or exclude CS_DROPSHADOW, and then call SetClassLongPtr with the changed flag value. But looking at that PInvoke definition, it is not trivial, especially taking into account 32/64-bit systems.

Can anybody give a link or a good example of this? And please, do not provide samples with overwriting CreateParams as this does not work for our dynamic scenario. Maybe, there is another [managed] way to do that?

回答1:

Here is something I have managed to write:

    private void SetSizeableCore(bool value)
    {
        fSizeable = value;
        if (value)
        {
            FormBorderStyle = FormBorderStyle.SizableToolWindow;
            DockPadding.All = 0;
            System.Version ver = Environment.OSVersion.Version;
            // Always for WinXP family, but for higher systems only if the aero theme is not in effect
            bool needShadow = ((ver.Major == 5) && (ver.Minor > 0)) || ((ver.Major > 5) && !IsAeroThemeEnabled());
            SetShadowFlag(needShadow);
        }
        else
        {
            FormBorderStyle = FormBorderStyle.None;
            DockPadding.All = 1;
            SetShadowFlag(true);
        }
    }

    private void SetShadowFlag(bool hasShadow)
    {
        if (!IsDropShadowSupported())
            return;
        System.Runtime.InteropServices.HandleRef myHandleRef = new System.Runtime.InteropServices.HandleRef(this, this.Handle);
        int myStyle = iGNativeMethods.GetClassLongPtr(myHandleRef, iGNativeMethods.CS_DROPSHADOW).ToInt32();
        if (hasShadow)
            myStyle |= iGNativeMethods.CS_DROPSHADOW;
        else
            myStyle &= ~iGNativeMethods.CS_DROPSHADOW;
        iGNativeMethods.SetClassLong(myHandleRef, iGNativeMethods.GCL_STYLE, new IntPtr(myStyle));
    }

    private bool IsDropShadowSupported()
    {
        // Win2000 does not have this feature
        if (Environment.OSVersion.Version <= new Version(5, 0))
            return false;
        bool myResult = false;
        iGNativeMethods.SystemParametersInfo(iGNativeMethods.SPI_GETDROPSHADOW, 0, ref myResult, 0);
        return myResult;
    }

    private bool IsAeroThemeEnabled()
    {
        if (Environment.OSVersion.Version.Major > 5)
        {
            bool aeroEnabled;
            iGNativeMethods.DwmIsCompositionEnabled(out aeroEnabled);
            return aeroEnabled;
        }
        return false; 
    }

Correct me if I'm wrong.