简体   繁体   English

C# Winform 点击通过

[英]C# Winform Click through

Right now, I have a simple form window.现在,我有一个简单的表格 window。 It is used to display a picture.它用于显示图片。

When I hover over the picture in this window, I want to set its opacity to 50%, and at the same time, set the mouse to penetrate.当我hover在这张window上的图片上,我想将它的不透明度设置为50%,同时设置鼠标穿透。 In this way, you can see the desktop content behind the picture and can click on it.这样就可以看到图片后面的桌面内容,可以点击了。

Main method:主要方法:

[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;
    }
}

In the code, when ishover, the setwindowlong method will be called, then the ishover will be false, and then it will be restored to unclickable.代码中,ishover时,会调用setwindowlong方法,则ishover为false,然后恢复为不可点击。 Then the hover will be detected again, and the loop will continue.然后再次检测到hover,循环继续。

The solution currently in mind is to add a hook to determine whether the mouse is hovering in the current window, and then do the corresponding processing.目前想到的解决方案是在当前的window上加一个hook判断鼠标是否悬停,然后做相应的处理。 Is there a more concise idea or api here?这里有更简洁的想法或 api 吗?

Used System.Runtime.InteropServices使用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);
         }
     }
   }
}

You will get a Transparent form and you will be able to click through it.你会得到一个透明的表格,你可以点击它。

Sample Output:样品 Output:

示例图像

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

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