VB.NET disable fade-in for forms

前端 未结 3 507
忘了有多久
忘了有多久 2020-12-21 18:25

I want to disable the form fade-in effect for a window. I think I found the right function

 _
Private Sh         


        
相关标签:
3条回答
  • 2020-12-21 19:18

    The documentation for DWMWA_TRANSITIONS_FORCEDISABLED reads:

    Use with DwmSetWindowAttribute. Enables or forcibly disables DWM transitions. The pvAttribute parameter points to a value of TRUE to disable transitions or FALSE to enable transitions.

    The macros TRUE and FALSE are declared as:

    #define FALSE 0
    #define TRUE  1
    

    So you need to pass 1 for the attrValue parameter.

    The boolean type that Windows uses natively is BOOL. This is declared like this:

    typedef int BOOL;
    

    And since sizeof(int) is 4, the attrSize you need to pass is 4.

    0 讨论(0)
  • 2020-12-21 19:23

    What works for me is

        If Environment.OSVersion.Version.Major >= 6 Then
            DwmSetWindowAttribute(Me.Handle, DWMWINDOWATTRIBUTE.DWMWA_TRANSITIONS_FORCEDISABLED, 1, 4)
        End If
    

    But that is just a guess. I am not sure if "1" stands for YES, and I am not sure if the length 4 is correct under all conditions. Having this confirmed would be great. Thank you!

    0 讨论(0)
  • 2020-12-21 19:25

    The function is awkward because of the attribute value argument type. It uses void*, typical for a C function that accepts different sized values. This is actually something you can easily deal with in VB.NET, you can write different overloads of the same function with different types for argument. The compiler then automatically figures out which one to call based on the argument you pass.

    Let's focus on the specific attribute you want to change, it is a BOOL value. So write an overload of the function that takes a Boolean, it is automatically marshaled to BOOL without you having to help:

    <DllImport("dwmapi.dll")> _
    Private Shared Function DwmSetWindowAttribute(ByVal hwnd As IntPtr, _
                ByVal attr As Integer, ByRef attrValue As Boolean, _
                ByVal attrSize As Integer) As Integer
    End Function
    

    Let's simplify the enum, you only need one of them:

    Private Const DWMWA_TRANSITIONS_FORCEDISABLED As Integer = 3
    

    Then you need to change the place where you call this function, a window can be created more than once but the Load event runs only once. You need to call it right after the window is created. Adding the error handling so you can diagnose runtime problems:

    Protected Overrides Sub OnHandleCreated(ByVal e As System.EventArgs)
        MyBase.OnHandleCreated(e)
        If Environment.OSVersion.Version.Major >= 6 Then
            Dim hr = DwmSetWindowAttribute(Me.Handle, _
                        DWMWA_TRANSITIONS_FORCEDISABLED, True, 4)
            If hr < 0 Then Marshal.ThrowExceptionForHR(hr)
        End If
    End Sub
    

    Worked well when I tested it.

    0 讨论(0)
提交回复
热议问题