日期:2014-05-18  浏览次数:21428 次

C# 同时实现窗体透明、鼠标穿透与嵌入桌面
正在写一个程序,希望实现窗体半透明和鼠标穿透功能,同时嵌入桌面,用了以下接口代码:
  [DllImport("user32", EntryPoint = "SetWindowLong")]
  private static extern uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);
  [DllImport("user32", EntryPoint = "GetWindowLong")]
  private static extern uint GetWindowLong(IntPtr hwnd, int nIndex);
  private const uint WS_EX_LAYERED = 0x80000;
  private const int WS_EX_TRANSPARENT = 0x20;
  private const int GWL_STYLE = (-16);
  private const int GWL_EXSTYLE = (-20);

  private void CanPenetrate(bool b)
  {
  uint intExTemp = GetWindowLong(this.Handle, GWL_EXSTYLE);
  //uint oldGWLEx = SetWindowLong(this.Handle, GWL_EXSTYLE, WS_EX_LAYERED | WS_EX_TRANSPARENT);
  uint oldGWLEx;
  if (b)
  oldGWLEx = SetWindowLong(this.Handle, GWL_EXSTYLE, intExTemp | WS_EX_TRANSPARENT| WS_EX_LAYERED);/////////穿透+透明
  else
  oldGWLEx = SetWindowLong(this.Handle, GWL_EXSTYLE, intExTemp | WS_EX_LAYERED);//透明
  }
同时设置窗口的Opacity属性可以实现鼠标穿透和窗口透明。

同时这个方法:
  [DllImport("User32.dll",EntryPoint="FindWindow")]  
  private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);  
  [DllImport("user32")]  
  private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);  
  //在构造函数中或者Load中  
  IntPtr hDeskTop=FindWindow("Progman", null); 
  SetParent(this.Handle,hDeskTop);
可以实现将窗体嵌入桌面,即按显示桌面不会消失。
但当把两个功能都用上的时候发现在设置Opacity属性时出现错误:
System.ComponentModel.Win32Exception: 参数不正确。
在 System.Windows.Forms.Form.UpdateLayered()
在 System.Windows.Forms.Form.set_Opacity(Double value)
在 事务提醒.Form1.Form1_Load(Object sender, EventArgs e) 位置 e:\Visual Studio 2008\Projects\事务提醒\事务提醒\Form1.cs:行号 180
不设置opacity的话就能成功嵌入桌面,但这样透明效果就没了(附带一句,我用的是vista)。
有没有人用过这两个方法,有碰到类似的问题吗?希望懂的帮忙解决下问题,谢谢了!

------解决方案--------------------
WS_EX_TRANSPARENT
这个参数就是这设置透明度的啊
------解决方案--------------------
Transparent, Click-Through Forms
http://www.codeproject.com/KB/vb/ClickThroughWindows.aspx

------解决方案--------------------
http://win.51aspx.com/CV/RotateTransformDemo/
------解决方案--------------------
透明只限于顶层窗体.嵌入桌面后,该窗体已经变成子窗体.
比较有效的方法是不嵌入窗体,只是拦截系统消息,屏蔽相关热键对自身窗体产生的消息.