winforms 如何使用DWMWA_ALLOW_NCPAINT

u4vypkhs  于 2022-11-17  发布在  其他
关注(0)|答案(1)|浏览(102)

我想使用DWMWA_ALLOW_NCPAINT在非客户端区域绘图,但我不知道如何使用它,有人能帮助我吗?

wnavrhmk

wnavrhmk1#

它是一个常量,您可以将其传递到Win32 API函数DwmSetWindowAttribute中。您不能将其与函数DwmGetWindowAttribute一起使用。它是“set only”。
若要从Managed程式码呼叫原生函式(在您的案例中是DwmSetWindowAttribute),您应该使用P/Invoke
在下面的代码中,您可以看到如何定义本机函数DwmSetWindowAttribute的签名并将常量DWMWA_ALLOW_NCPAINT传递给它。

PS:* 但是,我认为使用DWMWA_ALLOW_NCPAINT在非客户区绘图是不够的。在SO上有很多这样的主题。您可以搜索它。*

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace DWMWA_ALLOW_NCPAINT
{
    public partial class MainForm : Form
    {
        public Form1()
        {
            InitializeComponent();
        } 
        private IntPtr TRUE;
        private IntPtr FALSE;
  
        protected override void OnHandleCreated(EventArgs e)
        {
            TRUE = Marshal.AllocHGlobal(sizeof(int));
            Marshal.WriteInt32(TRUE, 1);
            FALSE = Marshal.AllocHGlobal(sizeof(int));
            Marshal.WriteInt32(TRUE, 0); 

            EnableNCPaint(Handle);
            //DisableNCPaint(Handle);
            base.OnHandleCreated(e);
        } 
        private void EnableNCPaint(IntPtr hwnd)
        {  
            DwmSetWindowAttribute(hwnd, (int)DWMWINDOWATTRIBUTE.DWMWA_ALLOW_NCPAINT, TRUE, sizeof(int)); 
        }
        private void DisableNCPaint(IntPtr hwnd)
        { 
            DwmSetWindowAttribute(hwnd, (int)DWMWINDOWATTRIBUTE.DWMWA_ALLOW_NCPAINT, FALSE, sizeof(int)); 
        } 
        enum DWMNCRENDERINGPOLICY
        {
            DWMNCRP_USEWINDOWSTYLE,
            DWMNCRP_DISABLED,
            DWMNCRP_ENABLED,
            DWMNCRP_LAST
        };
        [Flags]
        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
        };
        [DllImport("dwmapi.dll")]
        private static extern int DwmGetWindowAttribute(IntPtr hwnd, int dwAttribute, IntPtr pvAttribute, int cbAttribute);

        [DllImport("dwmapi.dll")]
        private static extern int DwmSetWindowAttribute(IntPtr hwnd, int dwAttribute, IntPtr pvAttribute, int cbAttribute); 
    }
}

相关问题