繁体   English   中英

C# Winform 点击通过

[英]C# Winform Click through

现在,我有一个简单的表格 window。 它用于显示图片。

当我hover在这张window上的图片上,我想将它的不透明度设置为50%,同时设置鼠标穿透。 这样就可以看到图片后面的桌面内容,可以点击了。

主要方法:

[DllImport("user32.dll")]
public static extern uint SetWindowLong(IntPtr h, int n, uint x);
    
void Update(){
    if (ishover)
    {
        Form.Opacity = 128;
        SetPenetrate(true);
    }
    else
    {
        Form.Opacity = 255,
        SetPenetrate(false);
    }
}

public void SetPenetrate(bool value)
{
    if (value)
    {
            SetWindowLong(this.Handle, -20, 0x20 | 0x80000);
    }
    else
    {
            this.FormBorderStyle = FormBorderStyle.None;
    }
}

代码中,ishover时,会调用setwindowlong方法,则ishover为false,然后恢复为不可点击。 然后再次检测到hover,循环继续。

目前想到的解决方案是在当前的window上加一个hook判断鼠标是否悬停,然后做相应的处理。 这里有更简洁的想法或 api 吗?

使用System.Runtime.InteropServices

using System.Runtime.InteropServices;

namespace TransparentWindow
{
  public partial class Form1 : Form
  {
     #region

     //The SendMessage function sends a message to a window or windows.
     [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
     static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

     //ReleaseCapture releases a mouse capture
     [DllImportAttribute("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]

     public static extern bool ReleaseCapture();
    
     #endregion

     public Form1()
     {
         InitializeComponent();
     }

     private void Form1_Load(object sender, EventArgs e)
     {
         this.BackColor = Color.Lime;
         this.TransparencyKey = Color.Lime;
     }

     private void Form1_MouseDown(object sender, MouseEventArgs e)
     {
         if (e.Button == MouseButtons.Left)
         {
             ReleaseCapture();
             SendMessage(this.Handle, 0xa1, 0x2, 0);
         }
     }
   }
}

你会得到一个透明的表格,你可以点击它。

样品 Output:

示例图像

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM