发新话题
打印

调用Windows API实现C#窗体透明代码

调用Windows API实现C#窗体透明代码

把前一段时间更新Service Master时打算写的窗体透明代码贴到这里

WinAPI.cs类文件,Invoke & Wrap了窗体透明所需要的API函数:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace TransForm
{
    class WinAPI
    {
        [DllImport("user32.dll")]
        public extern static IntPtr GetDesktopWindow();

        [DllImport("user32.dll")]
        public extern static bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
        public static uint LWA_COLORKEY = 0x00000001;
        public static uint LWA_ALPHA = 0x00000002;

        [DllImport("user32.dll")]
        public extern static uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);
        [DllImport("user32.dll")]
        public extern static uint GetWindowLong(IntPtr hwnd, int nIndex);

        public enum WindowStyle : int
        {
            GWL_EXSTYLE = -20
        }

        public enum ExWindowStyle : uint
        {
            WS_EX_LAYERED = 0x00080000
        }

    }
}

DeviceForm.cs单元是API函数的调用方式:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TransForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.SetWindowTransparent(100);
        }
        private void SetWindowTransparent(byte bAlpha)
        {
            try
            {
                WinAPI.SetWindowLong(this.Handle, (int)WinAPI.WindowStyle.GWL_EXSTYLE,
                    WinAPI.GetWindowLong(this.Handle, (int)WinAPI.WindowStyle.GWL_EXSTYLE) | (uint)WinAPI.ExWindowStyle.WS_EX_LAYERED);

                WinAPI.SetLayeredWindowAttributes(this.Handle, 0, bAlpha, WinAPI.LWA_COLORKEY | WinAPI.LWA_ALPHA);
            }
            catch
            {
            }
        }
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;

                cp.Parent = WinAPI.GetDesktopWindow();
                cp.ExStyle = 0x00000080 | 0x00000008;//WS_EX_TOOLWINDOW | WS_EX_TOPMOST

                return cp;
            }
        }
    }
}


不过其实WinAPI实现的窗体透明与修改Opacity属性得到的效果没有区别,我觉得更加经济实惠的方法是修改Opacity属性

TOP

发新话题

剑盟资讯 - 反病毒资讯门户|扑奔PPT - 扑奔PPT社区|网湛门户 - 湛江本地门户

鄂ICP备08102315号|粤湛网安备4408002113号

广东剑盟网络科技工作室 © 2004 - 2008 All Rights Reserved.

Powered by Discuz! Licensed