【C#】创建透明窗口实现夜间模式

夜间模式在手机上的应用很广泛,很多手机应用都添加了夜间模式的主题,但是在电脑上却很少有这样保护眼睛的主题,很多时候屏幕的背景颜色都是白色的,在晚上显得特别刺眼,如果可以调节屏幕光线的亮度的话,就可以让屏幕变暗,在一定程度上可以保护眼睛,但是在显示器上直接调节屏幕亮度显得特别麻烦,而Windows本身没有提供一些关于亮度的设置,也没有提供有关于显示器的一些编程接口,所以这方面的应用显得非常少,下面通过透明窗口,让屏幕加上一层蒙版达到调节屏幕明亮的目的,这个API找了好久才找到

代码比较简单,注释都在代码上,直接上代码

        public partial class MaskForm : Form
        {
            /*
             * 下面这段代码主要用来调用Windows API实现窗体透明(鼠标可以穿透窗体)
             */
            [DllImport("user32.dll", EntryPoint = "GetWindowLong")]
            public static extern long GetWindowLong(IntPtr hwnd, int nIndex);
            [DllImport("user32.dll", EntryPoint = "SetWindowLong")]
            public static extern long SetWindowLong(IntPtr hwnd, int nIndex, long dwNewLong);
            [DllImport("user32", EntryPoint = "SetLayeredWindowAttributes")]
            private static extern int SetLayeredWindowAttributes(IntPtr Handle, int crKey, byte bAlpha, int dwFlags);
            const int GWL_EXSTYLE = -20;
            const int WS_EX_TRANSPARENT = 0x20;
            const int WS_EX_LAYERED = 0x80000;
            const int LWA_ALPHA = 2; 
            

            public MaskForm()
            {
                InitializeComponent();
            }

            private void MaskForm_Load(object sender, EventArgs e)
            {
                // 取消窗体任务栏
                ShowInTaskbar = false;
                // 窗体位于Windows最顶部
                this.TopMost = true;
                // 去除窗体边框
                this.FormBorderStyle = FormBorderStyle.None;//5+1+a+s+p+x
                // 设置窗体最大化大小(除底部任务栏部分)
                this.MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
                // 设置Windows窗口状态为最大化模式
                this.WindowState = FormWindowState.Maximized;
                // 设置Windows属性
                SetWindowLong(this.Handle, GWL_EXSTYLE, GetWindowLong(this.Handle, GWL_EXSTYLE) | WS_EX_TRANSPARENT | WS_EX_LAYERED);
                SetLayeredWindowAttributes(this.Handle, 0, 100, LWA_ALPHA);

                this.BackColor = Color.Black;
            }

            public void SetOpacity(byte opacity)
            {
                SetLayeredWindowAttributes(this.Handle, 0, opacity, LWA_ALPHA);
            }
        }

当打开该窗口时,屏幕就会变暗

代码(vs2012)

https://files.cnblogs.com/bomo/%E5%A4%9C%E9%97%B4%E6%A8%A1%E5%BC%8F.zip

原文地址:https://www.cnblogs.com/bomo/p/2917085.html