四联光电智能照明论坛

标题: C#使用Windows API实现桌面上的遮罩层(鼠标穿透) [打印本页]

作者: Xiaoxue    时间: 2016-11-8 21:27
标题: C#使用Windows API实现桌面上的遮罩层(鼠标穿透)

C#实现实现桌面上的遮罩层(鼠标穿透)主要通过一下几个API函数来实现:GetWindowLong,SetWindowLong,SetLayeredWindowAttributes。其中有一个Windows 消息 WS_EX_TRANSPARENT 比较重要,它实现了鼠标穿透的功能。
下面来看看完整的实现代码:
  1. using System;    
  2. using System.Drawing;    
  3. using System.Windows.Forms;    
  4. using System.Runtime.InteropServices;    
  5. namespace WindowsApplication40    
  6. {    
  7.   public partia lclass Form1:Form    
  8.   {    
  9.     public Form1()    
  10.     {    
  11.       InitializeComponent();    
  12.     }    
  13.     [DllImport("user32.dll",EntryPoint="GetWindowLong")]    
  14.     public static extern long GetWindowLong(IntPtr hwnd,int nIndex);    
  15.     [DllImport("user32.dll",EntryPoint="SetWindowLong")]    
  16.     public static extern long SetWindowLong(IntPtr hwnd,int nIndex,long dwNewLong);    
  17.     [DllImport("user32",EntryPoint="SetLayeredWindowAttributes")]    
  18.     public static extern int SetLayeredWindowAttributes(IntPtr Handle,int crKey,byte bAlpha,int dwFlags);    
  19.     const int GWL_EXSTYLE=-20;    
  20.     const int WS_EX_TRANSPARENT=0x20;    
  21.     const int WS_EX_LAYERED=0x80000;    
  22.     const int LWA_ALPHA=2;    
  23.    
  24.     private void Form1_Load(objec tsender,EventArgs e)    
  25.     {    
  26.       this.BackColor=Color.Silver;    
  27.       this.TopMost=true;    
  28.       this.FormBorderStyle=FormBorderStyle.None;    
  29.       this.WindowState=FormWindowState.Maximized;    
  30.       SetWindowLong(Handle,GWL_EXSTYLE,GetWindowLong(Handle,GWL_EXSTYLE)|WS_EX_TRANSPARENT|WS_EX_LAYERED);    
  31.       SetLayeredWindowAttributes(Handle,0,128,LWA_ALPHA);    
  32.     }    
  33.   }    
  34. } 
复制代码

以上就是介绍C#使用Windows API实现桌面上的遮罩层(鼠标穿透),希望对你有所帮助。





欢迎光临 四联光电智能照明论坛 (http://5xhome.com/) Powered by Discuz! X3.2