Draw on the screen without a form

user1988147 picture user1988147 · Jan 17, 2013 · Viewed 43.2k times · Source

Is it possible to create a big white rectangle on the screen, without using a Forms Application?

It should cover the whole screen if possible. I know I have to use the System.Drawing and tried several steps, but none have actually printed anything to my screen!

Answer

Tharwen picture Tharwen · Jan 18, 2013

Method 1: Call the Windows API

You need System.Drawing and System.Runtime.InteropServices. You may need to add project references to them.

using System.Runtime.InteropServices;
using System.Drawing;

Add the methods to your class with P/Invoke

[DllImport("User32.dll")]
public static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("User32.dll")]
public static extern void ReleaseDC(IntPtr hwnd, IntPtr dc);

Get a Graphics object for the entire screen and draw a rectangle with it:

IntPtr desktopPtr = GetDC(IntPtr.Zero);
Graphics g = Graphics.FromHdc(desktopPtr);

SolidBrush b = new SolidBrush(Color.White);
g.FillRectangle(b, new Rectangle(0, 0, 1920, 1080));

g.Dispose();
ReleaseDC(IntPtr.Zero, desktopPtr);

The problem with this method is that if the screen refreshes at all, the rectangle will be overwritten, making it useless for most practical applications.

Method 2: Create a borderless form

As before, you need a project reference. This time to System.Windows.Forms. You'll also need System.Drawing again:

using System.Drawing;
using System.Windows.Forms;

Make the new form, remove its borders, fill the screen with it, and put it on top of the taskbar:

Form f = new Form();
f.BackColor = Color.White;
f.FormBorderStyle = FormBorderStyle.None;
f.Bounds = Screen.PrimaryScreen.Bounds;
f.TopMost = true;

Application.EnableVisualStyles();
Application.Run(f);

A possible issue with this is that the user can just alt+tab away from the window. If you want to do any more complicated graphics, you'll need to write some drawing code like this. To make the form background transparent, set its TransparentKey to the same as its Backolor.

I've just tested both of these in .NET 4.5 and Windows 7, so it may be different for earlier versions. More information here and here.