Is there an equivalent of Mac OS X Document modal sheet in .NET?

前端 未结 2 823
无人共我
无人共我 2021-01-15 13:58

My application has been getting more and more requests to have certain dialogs behave similar to Mac OS X Document modal Sheet functionality, where a dialog is modal to just

2条回答
  •  礼貌的吻别
    2021-01-15 14:13

    After revisiting this issue, I did some digging and found a hybrid solution that will work for my needs.

    I took the suggestion by p-daddy: https://stackoverflow.com/a/428782/654244

    And I modified the code to work for 32-bit and 64-bit compiles using the suggestion by hans-passant: https://stackoverflow.com/a/3344276/654244

    The result is the following:

    const int GWL_STYLE   = -16;
    const int WS_DISABLED = 0x08000000;
    
    public static int GetWindowLong(IntPtr hWnd, int nIndex)
    {
        if (IntPtr.Size == 4)
        {
            return GetWindowLong32(hWnd, nIndex);
        }
        return GetWindowLongPtr64(hWnd, nIndex);
    }
    
    public static int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong)
    {
        if (IntPtr.Size == 4)
        {
            return SetWindowLong32(hWnd, nIndex, dwNewLong);
        }
        return SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
    }
    
    [DllImport("user32.dll", EntryPoint = "GetWindowLong", CharSet = CharSet.Auto)]
    private static extern int GetWindowLong32(IntPtr hWnd, int nIndex);
    
    [DllImport("user32.dll", EntryPoint = "GetWindowLongPtr", CharSet = CharSet.Auto)]
    private static extern int GetWindowLongPtr64(IntPtr hWnd, int nIndex);
    
    [DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)]
    private static extern int SetWindowLong32(IntPtr hWnd, int nIndex, int dwNewLong);
    
    [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", CharSet = CharSet.Auto)]
    private static extern int SetWindowLongPtr64(IntPtr hWnd, int nIndex, int dwNewLong);
    
    
    public static void SetNativeEnabled(IWin32Window control, bool enabled)
    {
        if (control == null || control.Handle == IntPtr.Zero) return;
    
            NativeMethods.SetWindowLong(control.Handle, NativeMethods.GWL_STYLE, NativeMethods.GetWindowLong(control.Handle, NativeMethods.GWL_STYLE) &
                ~NativeMethods.WS_DISABLED | (enabled ? 0 : NativeMethods.WS_DISABLED));
    }
    
    public static void ShowChildModalToParent(IWin32Window parent, Form child)
    {
        if (parent == null || child == null) return;
    
        //Disable the parent.
        SetNativeEnabled(parent, false);
    
        child.Closed += (s, e) =>
        {
            //Enable the parent.
            SetNativeEnabled(parent, true);
        };
    
        child.Show(parent);
    }
    

提交回复
热议问题