小墨の博客

梦想需要付诸行动,否则只能是梦

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);
    }
}

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


来自:https://blog.csdn.net/weixin_33849942/article/details/85540587

张小弟之家

本文链接:
文章标题:

本站文章除注明转载/出处外,均为原创,若要转载请务必注明出处。转载后请将转载链接通过邮件告知我站,谢谢合作。本站邮箱:admin@only4.work

尊重他人劳动成果,共创和谐网络环境。点击版权声明查看本站相关条款。

    发表评论:

    搜索
    本文二维码
    标签列表
    站点信息
    • 文章总数:508
    • 页面总数:20
    • 分类总数:92
    • 标签总数:208
    • 评论总数:61
    • 浏览总数:225323

    | | |
    | |  Z-Blog PHP