In CSharp, on Windows 11, I have a form with a solid background and a transparent PictureBox. The form loads and PictureBox is actually transparent, but when I move the mouse over the transparent area the mouse handling gets sent to objects behind the form.
Since I want the form to handle mouse over events for transparent areas I added an override for WndProc which intercepts the NCHITTEST message and returns the HTCLIENT value of 1. I think this is correct based on Microsoft WM_NCHITTEST message Document.
With this updated WndProc I can see the messages from Form_MouseMove; but none from PictureBox_MouseMove. And objects visible through the transparent element behind the form are handling the mouse.
I suspect it is possible to intercept these the mouse control messages and force my form to handle them but I can’t seem to figure out how.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TransparentFormExample
{
public class TransparentForm : Form
{
private PictureBox pictureBox;
public TransparentForm()
{
// Set form properties
this.TransparencyKey = Color.LimeGreen;
this.Size = new Size(500, 800);
this.TopMost = true;
// Initialize and set PictureBox properties
pictureBox = new PictureBox
{
BackColor = Color.LimeGreen,
Size = new Size(200, 200),
Location = new Point(150, 300) // Centered in the form
};
// Add PictureBox to the form
this.Controls.Add(pictureBox);
// Add event handlers
this.MouseMove += new MouseEventHandler(Form_MouseMove);
pictureBox.MouseMove += new MouseEventHandler(PictureBox_MouseMove);
}
// Override WndProc to handle WM_NCHITTEST message
protected override void WndProc(ref Message m)
{
const int WM_NCHITTEST = 0x84;
const int HTCLIENT = 0x1;
if (m.Msg == WM_NCHITTEST)
{
m.Result = (IntPtr)HTCLIENT;
return;
}
base.WndProc(ref m);
}
private void Form_MouseMove(object sender, MouseEventArgs e)
{
Console.WriteLine("Mouse over form");
}
private void PictureBox_MouseMove(object sender, MouseEventArgs e)
{
// extra spaces to make it easier to spot if it happens
Console.WriteLine(" Mouse over PictureBox");
}
public void Start ()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
Application.Run( this );
}
}
}
I’m starting the form using the following PowerShell, since I do not have the ability to create a DLL, compile .cs, and am not allowed to run .exe files.
write-host "load main.cs"
add-type -path "TransparentForm.cs" -ReferencedAssemblies @(
"System.Windows.Forms"
"System.Drawing"
"System.Drawing.Primitives"
)
$ProgramInstance = [TransparentFormExample.TransparentForm]::New()
[System.Windows.Forms.Application]::Run( $ProgramInstance )
2