Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Forms: Pass clicks through a partially transparent always-on-top window

I am designing a window that is always on screen and around 20% opaque. It is designed to be a sort of status window, so it is always on top, but I want people to be able to click through the window to any other application below. Here's the opaque window sitting on top of this SO post as I type right now:

Example

See that grey bar? It would prevent me from typing in the tags box at the moment.

like image 758
Sam Weaver Avatar asked Oct 04 '16 15:10

Sam Weaver


1 Answers

You can make a window, click-through by adding WS_EX_LAYERED and WS_EX_TRANSPARENT styles to its extended styles. Also to make it always on top set its TopMost to true and to make it semi-transparent use suitable Opacity value:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.Opacity = 0.5;
        this.TopMost = true;
    }
    [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);
    const int GWL_EXSTYLE = -20;
    const int WS_EX_LAYERED = 0x80000;
    const int WS_EX_TRANSPARENT = 0x20;
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        var style = GetWindowLong(this.Handle, GWL_EXSTYLE);
        SetWindowLong(this.Handle,GWL_EXSTYLE , style | WS_EX_LAYERED | WS_EX_TRANSPARENT);
    }
}

Sample Result

enter image description here

like image 60
Reza Aghaei Avatar answered Nov 11 '22 06:11

Reza Aghaei