C# SetOpacity / 設定視窗透明度,

來源:互聯網
上載者:User

C# SetOpacity / 設定視窗透明度,
先行調用“取視窗屬性 /GetWindowLong”取得視窗的“視窗擴充風格 /GWL_EXSTYLE”屬性值,位或(bor)“視窗擴充分層 /WS_EX_LAYERED”屬性值,後調用“置視窗屬性 /SetWindowLong”設定新的ExStyle“置視窗分層透明度/ SetLayeredWindowAttributes”後傳遞“Alpha /LWA_ALPHA”透明表單 具體參照MSDN

protected override void OnLoad(EventArgs e){    // base.Opacity = 0.9f;    SetOpacity((int)base.Handle, (255 / 100) * 90);}


上面的範例程式碼兩者功能相同,設定視窗透明度

        private static void SetOpacity(int hWnd, byte bAlpha)        {            int dwExStyle = NativeMethod.GetWindowLong(hWnd, NativeMethod.GWL_EXSTYLE);            dwExStyle |= NativeMethod.WS_EX_LAYERED;            NativeMethod.SetWindowLong(hWnd, NativeMethod.GWL_EXSTYLE, dwExStyle);            if (!NativeMethod.SetLayeredWindowAttributes(hWnd, 0, bAlpha, NativeMethod.LWA_ALPHA))                throw new Exception("Unable to set the Window Opacity.");        }
public abstract class NativeMethod        {            [DllImport("user32.dll", SetLastError = true)]            [return: MarshalAs(UnmanagedType.Bool)]            public static extern bool SetLayeredWindowAttributes(int hwnd, int crKey, byte bAlpha, int dwFlags);            [DllImport("user32.dll", SetLastError = true)]            public static extern int GetWindowLong(int hwnd, int nlndex);            [DllImport("user32.dll", SetLastError = true)]            public static extern int SetWindowLong(int hwnd, int nlndex, int dwNewLong);            public const int LWA_ALPHA = 2;            public const int LWA_COLORKEY = 1;            public const int GWL_EXSTYLE = -20;            public const int WS_EX_TRANSPARENT = 32;            public const int WS_EX_LAYERED = 524288;        }



 

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.