Creating a Transparent Form - arcdev/engram404 GitHub Wiki

originally posted 2016-04-17 at https://engram404.net/creating-a-transparent-form/

If you already know why you're here, you might want to skip to The good stuff.

Background

As part of my Cross Hairs exploration (read more) I need to create a full screen, top-level, transparent form.

'"What,'" you ask, '"would I do with a transparent form?'"

Well, think of a transparent form as an overlay (because it's, um, transparent).  That means that any controls you have on the form show up over top of anything else.  That means you could have some fun with it.  The simple, and admittedly contrived example is using a transparent form to measure anything on the screen (without having to take a screenshot and move it into an image editing tool.  Just to give you an example, here's a clipping from MDN.  I've drawn a red box around it (using Paint.NET).

image

(sure there are ways to measure web page elements, but just bear with me)

I created a simple WinForms app with a transparent form and a few controls (source code here) that looks like this (while sitting in Visual Studio):

image

When I run this and resize the form over the same block on the MDN page, you see this:

image

Yup. It can be fancier and do more, but hopefully you get the idea.

Here are some other ideas, if you care to play with them:

  • draw on the screen almost like an old transparency or whiteboard – great for presentations
  • place a grid over your screen for alignments
  • measure distances between two points
  • generate guidelines
  • black out something on your screen when sharing or recording your screen
  • add a color filter to change the colors of the screen to emulate a color blind individual

The good stuff

It turns out that it's pretty simple to cover the majority of that, by using the Visual Studio designer and the Properties tool. You set things as follows:

  • FormBorderStyle = None
  • StartPosition = Manual
  • Location = 0,0
  • TopMost = True
  • TransparencyKey = Control (or whatever BackColor is set to; the default is Control)

To make this transparent (invisible) form cover the entire screen, you'll want to set the Width and Height in one of the Form events (like OnLoad). I did this with this code:

var bounds = Screen.GetBounds(new Point(0, 0));
Width = bounds.Width;
Height = bounds.Height;

Of course, this only works for a single monitor.  For folks with multiple monitors, it actually gets simpler (by using System.Windows.Forms.SystemInformation.VirtualScreen):

var bounds = SystemInformation.VirtualScreen;
Width = bounds.Width;
Height = bounds.Height;

PS – somewhere along the way, I thought I had set the TransparencyKey value to the same as the BackColor and it didn't work.  Instead, I had to set them each to an entirely different color (e.g. Red).  But after a quick re-test, it seem they work just fine leaving them both at Control.