Clickthrough to desktop on a transparent form

北城余情 提交于 2019-12-04 07:49:55
Tamas Henning

I managed to find a proper solution for this problem after looking very deeply into this. It turns out with the proper Win32 API calls it is possible to set a form "Invisible" to mouse clicks. This can be achieved by:

[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);

[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

[DllImport("user32.dll")]
static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);

public void SetFormTransparent(IntPtr Handle) {
    oldWindowLong = GetWindowLong(Handle, GWL_EXSTYLE);
    SetWindowLong(Handle, GWL_EXSTYLE, Convert.ToInt32(oldWindowLong | WS_EX_LAYERED | WS_EX_TRANSPARENT));
}

public void SetFormNormal(IntPtr Handle) {
    SetWindowLong(Handle, GWL_EXSTYLE, Convert.ToInt32(oldWindowLong | WS_EX_LAYERED));
}

But there is a trick to everything. You need to be careful that all clicks made on the forum will fall through the form and be sent to anything below the form. To ensure that if I click on my form e.g. on a button and I want the button clicked I did a simple trick. I have a timer in the background running every N milliseconds and analyzing the position of the Cursor. If it's above the area I want it to be, it'll set the Form to Normal via SetFormNormal() otherwise it'll be transparent.

Hope this code bit helps and people will use it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!