Windows Mobile,个人心中臻至完美的系统。
不忍自己对WM的钻研成果消逝,故留作纪念。
系列开篇,便是一个曾令自己困扰很久的问题:如何实现半透明窗体。
如果了解Win32编程,其实很简单。
主要用到了三个方法:
SetLayeredWindowAttributes
GetWindowLong
SetWindowLong
核心代码:
1 private void SetWindowTransparent(byte bAlpha)
2 {
3 SetWindowLong(this.Handle, (int)WindowStyle.GWL_EXSTYLE,
4 GetWindowLong(this.Handle, (int)WindowStyle.GWL_EXSTYLE) | (uint)ExWindowStyle.WS_EX_LAYERED);
5
6 SetLayeredWindowAttributes(this.Handle, 0, bAlpha, LWA_ALPHA);
7 }
效果:
完整代码:
1 using System;
2
3 using System.Collections.Generic;
4 using System.ComponentModel;
5 using System.Data;
6 using System.Drawing;
7 using System.Text;
8 using System.Windows.Forms;
9 using System.Runtime.InteropServices;
10
11 namespace Demo01
12 {
13 public partial class Form1 : Form
14 {
15 public Form1()
16 {
17 InitializeComponent();
18 }
19
20 [DllImport("coredll.dll")]
21 public extern static IntPtr GetDesktopWindow();
22
23 [DllImport("coredll.dll")]
24 public extern static bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
25 public static uint LWA_COLORKEY = 0x00000001;
26 public static uint LWA_ALPHA = 0x00000002;
27
28 [DllImport("coredll.dll")]
29 public extern static uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);
30 [DllImport("coredll.dll")]
31 public extern static uint GetWindowLong(IntPtr hwnd, int nIndex);
32
33 public enum WindowStyle : int
34 {
35 GWL_EXSTYLE = -20
36 }
37
38 public enum ExWindowStyle : uint
39 {
40 WS_EX_LAYERED = 0x00080000
41 }
42
43 private void SetWindowTransparent(byte bAlpha)
44 {
45 try
46 {
47 SetWindowLong(this.Handle, (int)WindowStyle.GWL_EXSTYLE,
48 GetWindowLong(this.Handle, (int)WindowStyle.GWL_EXSTYLE) | (uint)ExWindowStyle.WS_EX_LAYERED);
49
50 SetLayeredWindowAttributes(this.Handle, 0, bAlpha, LWA_ALPHA);
51
52 }
53 catch
54 {
55 }
56 }
57
58 private void button1_Click(object sender, EventArgs e)
59 {
60 this.Close();
61 }
62
63 private void trackBar1_ValueChanged(object sender, EventArgs e)
64 {
65 label1.Text = "透明度(0~255): " + trackBar1.Value.ToString();
66 SetWindowTransparent(Convert.ToByte(trackBar1.Value));
67 }
68
69 private void Form1_Load(object sender, EventArgs e)
70 {
71 Rectangle rf = Screen.PrimaryScreen.WorkingArea;
72
73 this.Location = new Point((rf.Width - this.Width) / 2, (rf.Height - this.Height) / 2);
74
75 //SetWindowTransparent(136);
76 }
77 }
78 }
工程文件:
https://files.cnblogs.com/files/lesliexin/01.%E5%8D%8A%E9%80%8F%E6%98%8E%E7%AA%97%E4%BD%93.7z
来源:oschina
链接:https://my.oschina.net/u/4358445/blog/3421055