代码人生的小狗窝

一行行枯燥的代码,却描绘出人生的点点滴滴

您现在的位置是:首页>_C#

设置一个文件夹的透明度解决办法

发布时间:2019-11-22浏览(996)

    设置一个文件夹的透明度
    就是得一个窗体,如打开了一个word,或者文件夹。然后写一个代码设置它的透明度。这样可以吗?

    ------解决方案--------------------
    记事本为例,参考:
    C# code
    using System.Runtime.InteropServices;
    
    [DllImport("user32.dll")]
    private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
    [DllImport("user32.dll")]
    private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpszClass, string lpszWindow);
    [DllImport("user32.dll")]
    public static extern bool SetLayeredWindowAttributes(
        IntPtr hWnd, int crKey, byte bAlpha, int dwFlags);
    [DllImport("user32.dll")]
    public static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprcUpdate, 
        IntPtr hrgnUpdate, uint flags);
    
    public const int GWL_EXSTYLE = -20;
    public const int WS_EX_LAYERED = 0x00080000;
    public const int LWA_ALPHA = 0x00000002;
    public const int RDW_INVALIDATE = 1;
    public const int RDW_ERASE = 4;
    public const int RDW_ALLCHILDREN = 0x80;
    public const int RDW_FRAME = 0x400;
    
    private void button1_Click(object sender, EventArgs e)
    {
        //设置透明
        IntPtr vHandle = FindWindow("Notepad", null);
        SetWindowLong(vHandle, GWL_EXSTYLE,
            GetWindowLong(vHandle, GWL_EXSTYLE) | WS_EX_LAYERED);
        SetLayeredWindowAttributes(vHandle, 0, 255 / 2/*透明度*/, LWA_ALPHA); 
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
        //恢复
        IntPtr vHandle = FindWindow("Notepad", null);
        SetWindowLong(vHandle, GWL_EXSTYLE,
            GetWindowLong(vHandle, GWL_EXSTYLE) & ~WS_EX_LAYERED);
        RedrawWindow(vHandle, IntPtr.Zero, IntPtr.Zero,
            RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
    }
    
    ------解决方案--------------------
    楼主别忘了把答案贴上来啊,让我们也学习学习,谢谢
    ------解决方案--------------------
    SetLayeredWindowAttributes