Windows Mobile,个人心中臻至完美的系统。
不忍自己对WM的钻研成果消逝,故留作纪念。
系列开篇,便是一个曾令自己困扰很久的问题:如何实现半透明窗体。
如果了解Win32编程,其实很简单。
主要用到了三个方法:
SetLayeredWindowAttributes
GetWindowLong
SetWindowLong
核心代码:
private void SetWindowTransparent(byte bAlpha)
{
SetWindowLong(this.Handle, (int)WindowStyle.GWL_EXSTYLE,
GetWindowLong(this.Handle, (int)WindowStyle.GWL_EXSTYLE) | (uint)ExWindowStyle.WS_EX_LAYERED); SetLayeredWindowAttributes(this.Handle, , bAlpha, LWA_ALPHA);
}
效果:
完整代码:
using System; using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices; namespace Demo01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} [DllImport("coredll.dll")]
public extern static IntPtr GetDesktopWindow(); [DllImport("coredll.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("coredll.dll")]
public extern static uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);
[DllImport("coredll.dll")]
public extern static uint GetWindowLong(IntPtr hwnd, int nIndex); public enum WindowStyle : int
{
GWL_EXSTYLE = -
} public enum ExWindowStyle : uint
{
WS_EX_LAYERED = 0x00080000
} private void SetWindowTransparent(byte bAlpha)
{
try
{
SetWindowLong(this.Handle, (int)WindowStyle.GWL_EXSTYLE,
GetWindowLong(this.Handle, (int)WindowStyle.GWL_EXSTYLE) | (uint)ExWindowStyle.WS_EX_LAYERED); SetLayeredWindowAttributes(this.Handle, , bAlpha, LWA_ALPHA); }
catch
{
}
} private void button1_Click(object sender, EventArgs e)
{
this.Close();
} private void trackBar1_ValueChanged(object sender, EventArgs e)
{
label1.Text = "透明度(0~255): " + trackBar1.Value.ToString();
SetWindowTransparent(Convert.ToByte(trackBar1.Value));
} private void Form1_Load(object sender, EventArgs e)
{
Rectangle rf = Screen.PrimaryScreen.WorkingArea; this.Location = new Point((rf.Width - this.Width) / , (rf.Height - this.Height) / ); //SetWindowTransparent(136);
}
}
}
全部代码
工程文件:
https://files.cnblogs.com/files/lesliexin/01.%E5%8D%8A%E9%80%8F%E6%98%8E%E7%AA%97%E4%BD%93.7z